let names = [];
let isOver = false;
while (!isOver) {
let name = prompt("Enter another name or press cancel.");
if (name != null) {
names.push(name);
} else {
isOver = true;
}
}
for (let i = 0; i < names.length; i++) {
console.log(names[i]);
}
If I change the vaiable ‘isOver’ value to true, I will also change the while condition to (isOver) and else to isOver = false;
let names = [];
let isOver = true;
while (isOver) {
let name = prompt("Enter another name or press cancel.");
if (name != null) {
names.push(name);
} else {
isOver = false;
}
}
for (let i = 0; i < names.length; i++) {
console.log(names[i]);
}
I just want to know why used ‘false’ in the first place?
2
Answers
While either way works technically, the way the original code is written makes more sense lexically:
ie, keep doing this until it’s finished. If you want to switch to using the 2nd block, a name change of the variable would help, eg:
It makes no difference to the execution of the code, but a world of difference to future readers/maintainers of the code.
Personally I’d stick with the first one, using the features of the language to define the not (
!
), as when you’re setting the flag, I believe this:is easier to read and make more sense of than:
In the first version of the code,
isOver
is initially set to false, meaning the loop is not over and should continue to run.The while loop condition checks if isOver is not
true
(!isOver
), so the loop will continue running untilisOver
becomestrue
.This happens when the user doesn’t enter a name, at which point
isOver
is set to true, and the loop ends.In the second version of the code, you’ve inverted the logic.
isOver
is now initially set totrue
, meaning the loop is over.However, the condition in the while loop is now checking if
isOver
istrue
, so the loop will continue running as long asisOver
istrue
. This time, when the user doesn’t enter a name,isOver
is set tofalse
, and the loop ends.The reason to use
false
in the first place has more to do with readability and intuitive understanding of the code. Most developers will understand the flagisOver
to represent completion, so having it set totrue
when the task is complete makes sense. This is why the initial state ofisOver
is false in the first place – because the task (in this case, the while loop) is not yet complete. If you invert this logic, it might confuse other developers who read your code later.