Evaluating a falsy value in JS. | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 2

Evaluating a falsy value in JS.

Let's say I have a boolean variable called: let gameOver = false; My question is, if I want to evaluate the gameOver variable like this: if (!gameOver) {...} ¿What exactly I'm evaluating? ¿If the variable gameOver is false?

27th Jan 2021, 3:59 PM
Alex A.
Alex A. - avatar
3 Antworten
+ 7
Yes, you would be saying "If the game is not over..." because this will first check the value of gameOver, and then reverse it, so that if it is true, it will return false and if it is false, then it will return true. Then, the if statement checks if the result of the operation was true and if it was, execute the code below. Another way of seeing it is: gameOver = false = gameOver is equal to true = false !gameOver = true = not gameOver is equal to true = true because gameOver is false if not (gameOver is equal to true), then execute some code, otherwise don't. I hope this clarifies things!!
27th Jan 2021, 4:20 PM
Paula Campbell
Paula Campbell - avatar
+ 5
!true is always false and !false is always true. So if `gameOver` is true, !gameOver will be false and the if-block will not be executed. It's the complete opposite if `gameOver` is true
27th Jan 2021, 4:21 PM
XXX
XXX - avatar
+ 2
!gameOver <=> gameOver==false return true for any falsy value (including undefined, null, 0...)
27th Jan 2021, 6:07 PM
visph
visph - avatar