Search code examples
javascriptloopswhile-loopoperatorslogical-operators

OR and AND operator confusion in Javascript


I was coding along Colt Steele's Web developer bootcamp. This is the original file [link] I was confused on line 5, while loop on line 5 continues as long as we don't type "quit" or "q". It requires only one thing "quit" or "q" to close the loop, when I type either "quit" or "q" loop closes. Only one thing to close the loop ("quit" or "q") But I read that AND need both conditions in order to be true. Isn't it ? And when I use || instead of && it behaves oddly. Can anyone explain plz? Thank you in advance.


Solution

  • If it helps you to understand, you can rewrite it from AND to OR:

    while (command != "quit" && command != "q") {
      // do job
    }
    

    is equivalent to

    while (!(command === "quit" || command === "q")) {
      // do job
    }
    

    https://en.wikipedia.org/wiki/De_Morgan%27s_laws