Home > Mobile >  how Exclamation mark before a falsy value works in if condition
how Exclamation mark before a falsy value works in if condition

Time:11-11

I found this when I was watching a project tutorial.

let isGameOver = false;

if(!isGameOver){
console.log('game goes on.')
}
if(isGameOver){
console.log('game over')
}

Inside this block, it seems "!" didn't negate the return of isGameOver. It is more working like : if(isGameOver == false){...} //they are working functionally same. if(!isGameOver){....} so why it didn't nagate isGameOver to truthy value like

 if(isGameOver == true) 

CodePudding user response:

! negates the value.

Therefore if "isGameOver" is false, then "!isGameOver" is "true", which is why it passes the true condition in the first if.

CodePudding user response:

It's working just as it should. First though, understand that using the logical NOT operator (!) doesn't change the value of the item it is placed in front of - - it creates a new value to be used just in that expression. In other words after using !isGameOver in one expression, the value of that variable remains unchanged for future expressions. If you wanted to change the value of the variable, you'd write: isGameOver = !isGameOver;.

Your variable is set to false initially and then you check it for ! (not), which would mean true. Since true is always true, the first consoloe.log() will fire. Then, your second test tests against false (the variable value) and since false is never true, the second console.log() doesn't fire:

let isGameOver = false;

// Check to see if the opposite of isGameOver (false) is true (which it is):
if(!isGameOver){
  console.log('game goes on.')
}

// Check to see if isGameOver is true (which it isn't):
if(isGameOver){
  console.log('game over')
}

  • Related