Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

105
Views
A single global variable that is always a random number each time it's referenced

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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())
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!