'Why when I pass "q" the second time into my input it does not break the loop?
It works the first time when I pass "q" into my input, but after that, it no longer works. Why? Appreciate any kind advice.
alert("Welcome to your To-Do List!")
let userInput = prompt("What would you like to do?");
let toDo = [];
while (userInput != "q") {
let userInput = prompt("What would you like to do?");
console.log(userInput);
}
Solution 1:[1]
Because you're declaring a new userInput variable inside the loop, you need to re-assign to the same variable.
alert("Welcome to your To-Do List!")
let userInput = prompt("What would you like to do?");
let todos = [];
while (userInput != "q") {
todos.push(userInput);
userInput = prompt("What would you like to do?");
}
console.log(todos);
Solution 2:[2]
Because you have defined userInput variable inside the while loop again. This makes it locally scoped for the while loop. Just remove let before the variable userInput in while loop.
Solution 3:[3]
The problem is that third let. It's creating another userInput, scoped to that inner block, which shadows the outer one.
Try changing it to:
alert("Welcome to your To-Do List!")
let userInput = prompt("What would you like to do?");
let toDo = [];
while (userInput != "q") {
userInput = prompt("What would you like to do?");
console.log(userInput);
}
You can read more about let here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | SSM |
| Solution 2 | Daljit Kumar |
| Solution 3 | Scovetta |
