Home > Software engineering >  how can I access the variable 'night' in from the while loop javascript
how can I access the variable 'night' in from the while loop javascript

Time:05-11

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

CodePudding user response:

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);
[...]

CodePudding user response:

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.

CodePudding user response:

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>

  • Related