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

333
Visualizações
how can I access the variable 'night' in from the while loop javascript

isValid = false;

while (isValid == false) {

  let night = Number(window.prompt("pick a night"));
  if (typeof night == 'number' && night >= 1 && night <= 8) {
    isValid = true;
  }
}

document.write(night); //not accessible

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You must define variable night outside of the while loop, like this:

[...]
let night
let isValid = false;

while(isValid == false) {
    night = Number(window.prompt("pick a night"));
    if(typeof night == 'number' && night >= 1 && night <= 8){
        isValid = true;
    }
}
 
document.write(night);
[...]
about 4 years ago · Juan Pablo Isaza Relatório

0

let is a block scope variable i.e. it will only be accessible in the while loop. If you want to access it outside the while loop, declare it as a var variable which is a global scope.

about 4 years ago · Juan Pablo Isaza Relatório

0

To be honest, I wouldn't even recommend using a while loop.

Also, one issue with your code is that you are checking if typeof night === 'number', but it will always be number since you wrapped the value in Number(). NaN itself is of the number type.

<script>
    const getNight = () => {
        const night = +window.prompt('Pick a night:');

        if (isNaN(night) || night < 1 || night > 8) {
            alert('Try again.');
            return getNight();
        }

        return night;
    };

    document.write(getNight());
</script>

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