skip to Main Content
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


  1. While either way works technically, the way the original code is written makes more sense lexically:

    while (!isOver)
    

    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:

    while (notOver)
    

    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:

    isOver = true;
    

    is easier to read and make more sense of than:

    notOver = false;
    
    Login or Signup to reply.
  2. 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 until isOver becomes true.
    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 to true, meaning the loop is over.

    However, the condition in the while loop is now checking if isOver is true, so the loop will continue running as long as isOver is true. This time, when the user doesn’t enter a name, isOver is set to false, 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 flag isOver to represent completion, so having it set to true when the task is complete makes sense. This is why the initial state of isOver 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search