When i use var instead of let the following code works fine and prompt the user to type text until he enters the word "exit". However using the let when i type the second time the word "exit" it doesn't.
let text = prompt("write something");
while(text !== "exit")
{
let text = prompt("write something");
}
console.log("end of program);
Don't use anything when you reset text
let text = prompt("write something");
while(text !== "exit")
{
text = prompt("write something"); // nothing, uses text in outer scope
}
console.log("end of program);
When you use 'let' in the while loop you are creating a separate variable scoped to that statement block. When you use var, it is hoisted to the function, or to the global object if not in a function (or if you don't use var, let, or const and just attempt to use a variable without declaring it). Since the variables are in the same function (or global scope) using var, they refer to the same thing.
When using let, the variable is scoped to the block of code. So the 'text' variable inside the while statement block does not refer to the same 'text' variable declared outside that block and used in the while condition. Here's the example from the link:
let x = 1;
if (x === 1) {
let x = 2;
console.log(x);
// expected output: 2
}
console.log(x);
// expected output: 1