You can’t handle the truth!

JavaScript can’t either, which is why it uses type coercion to convert most values to a ‘truthy’ value. What does this mean?

Well, the true boolean value is just ‘true’, right? That is accurate, but it’s good to know that JavaScript also interprets the majority of other values to be true as well. Meaning, if they are place in an if statement, JavaScript will go ahead and run the if statement because the statement isn’t false.

Obviously JavaScript interprets the boolean value ‘false’ to be false. But there are a few values in JavaScript that are interpreted to be falsy, and as such, JavaScript will not run an if statement that is dependent upon these values. The values are:

  • 0
  • ””
  • null
  • undefined
  • NaN

Other than being a handy little bit of trivia, what is this useful for? Well it’s not something that will always be useful, but it’s definitely worth filing away for future reference. Here’s an example of a use-case I ran into lately.

Recently I wrote a game for a friend’s baby shower. (You can play it here, if you’re interested. Or you can check out the code here.)

One version of the game included pausing when the player jumped on the bad guy. I wanted the bad guy to be destroyed on unpause. But the problem I was running into was that Phaser, the platform I used to build the game, runs the update function pretty much constantly, and I have to destroy the villager in the update function (because it’s called immediately after the game is unpaused).

But here’s the rub: there wasn’t always a villager that needed destroying. Since that was coming back undefined, my whole game was breaking.

Having the falsy value trivia tucked away, I was able to work around this relatively easily.


if(currentVillager) {
	currentVillager.destroy();
}

In the function where the player jumps on the villager, I pass that specific villager to a variable called ‘currentVillager’. Then in the update function, I have an if statement checking for ‘currentVillager’. Lucky for me, JavaScript interprets undefined as a falsy value, and skips my code if there isn’t a villager in the ‘currentVillager’ variable.

Pretty handy!

TL;DR

If you have some code that only needs to be executed if a variable has a value (or isn’t undefined), you can wrap this code in an if statement and take advantage of truthy and falsy values!

Questions? Tweet me!