Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

95
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda