Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

318
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!