Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

102
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda