Why does the following code work? (JavaScript)

built

//
BuSo Pro
Boot Camp
Joined
Jan 23, 2015
Messages
1,677
Likes
1,442
Degree
4
Ok I'm pretty confused right now but I have a question about the following while loop:

Code:
while(input !== "stop"){
    var input = prompt("Input something");
}

How come the code works but the variable is defined inside the loop? The while loop condition variable was not yet defined (in the first line of code) so surely that should throw an error?

Wouldn't I have to define the input variable outside and before the while loop?
 
not with modern languages. (well, not all of them)

But even then, it would not need to be

as input == "not defined" is still !== "stop"
 
Yep it depends on the language. In some languages it would trigger an error, in some it would loop forever because of scoping, in some it would work fine.
 
The way you have it set it will return this error:
Code:
Uncaught ReferenceError: input is not defined

It's because you're calling "input" without defining it. You'll need to set the variable "input" before the while loop instead of setting it inside the while loop.

If you adjust the code to look like this:
Code:
var input;

while(input !== "stop") {
    input = prompt("Input something");
};

It'll work.

EDIT: Wow, I'm a dummy. I misread your question.
 
Last edited:
Thanks for the replies.

---

Here's a full explanation of why it works if anyone cares to know why it works:

This surprised me, too, so I threw it up on StackOverflow. The answer I got comes from the Mozilla documentation:

Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.

Hope this helps!
 
Back