Home > Software engineering >  A single global variable that is always a random number each time it's referenced
A single global variable that is always a random number each time it's referenced

Time:05-11

I'd like to use one global variable that is random every time it's used. My current method creates a random number once and that number stays the same. I don't need the number to be unique, just always random.

var randomNumber = Math.floor(Math.random() * 100);
$('something').css('width', randomNumber)
$('something-else').css('width', randomNumber) // want a different random number
$('a-totally-different-thing').css('width', randomNumber) // want another different random number

Is there a way to do this, or do I have to use a different var each time? My main reason for wanting this is to keep the code clean and readable and not have to put Math.floor(Math.random() * 100) in over and over again everywhere. I'm experimenting with generative art so it's going to be used a LOT. I'd like it to be global so I can reference it from anywhere.

Answer: Use a function instead of a variable. Much Thanks to VLAZ and CherryDT

CodePudding user response:

You can define a getter on the global object:

Object.defineProperty(globalThis, 'randomNumber', {
  get: () => Math.floor(Math.random() * 100)
})

console.log(randomNumber)
console.log(randomNumber)
console.log(randomNumber)

...but I find this odd and would actually see this as unexpected, confusing behavior if I'd encounter it in code. Why not using a function instead?

function getRandomNumber () {
  return Math.floor(Math.random() * 100)
}

console.log(getRandomNumber())
console.log(getRandomNumber())
console.log(getRandomNumber())
  • Related