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

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

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 Denunciar

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 Denunciar

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 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