I apologize in advance, this might have been discussed on StackOverflow before, I just do not know what this is called, so I could not find a satisfactory answer.
However, I am learning JavaScript and with a book called “Eloquent JavaScript”. There I found the following piece of code, which repeatedly prompts the user to enter his name until he did it.
while (!input) {
var input = prompt("Who are you?");
}
I simply do not understand why this actually works instead of raising an error. At the time the condition expression is being evaluated, there is no variable called input out there. If I understand it right, there is no evaluation possible, which would normally prevent further execution. The statement in the while loop’s body, which then creates a variable called input, is still being executed, though.
However, this made me anxious, so I tried this:
while (!bool) {
console.log("Hi");
var bool = true;
}
This is even weirder. It’s same problem when it comes to the condition expression: bool is being created within the scope of the loop’s body, after the evaluation of the condition. And secondly, bool is constantly set to be true, but still the code is being executed once, in other words, Hi is being printed once.
I am confused and would appreciate some help. 😉
This is one of Javascript’s little eccentricities. The key thing to remember is that, in Javascript, variables are not necessarily created at the point in the code where
var x =appears. They are always created at the top of the scope. This means at the beginning of the function that contains them, or the top of the global scope if that’s the scope we’re working in. This is called hoisting.So your code may look like this:
But it will run like this:
(Remember that there is no such thing as block scope in Javascript.)
The first time,
boolisundefined.!undefinedistrue, so the conditional passes. After that,boolistrue, so the conditional fails. It is a similar story withinputin your first example.The variable will always be created at the very top of the scope, no matter where it is declared. For this reason, it is sometimes recommended as good practice to declare your variables at the top of the scope, since that is where Javascript will consider them to be. This prevents surprises like the one you cite.