The Truth about JavaScript

Every value in JavaScript is intrinsically truthy or falsey. Saying a value is truthy is like saying “hey buddy, I know you’re not actually the boolean value true, but if anyone asks I’ll just sort of pretend that you are”. Likewise for falsey.

JavaScript has exactly six falsey values: 0, NaN, '' (empty string), null, undefined, and of course the boolean value false. Everything else is truthy. This includes (possibly unexpected) values like the string 'false', -1, and empty arrays.

Be Concise

Knowing all this will let you write (and understand) more concise code. Compare the if statements below.

// assuming str is used to hold a string

if (str !== undefined && str !== null && str.length > 0) {
    console.log('str is a non-empty string');

if (str) {
    console.log('str is a non-empty string');

Here’s another example. It’s not uncommon to see terse feature detection that relies on the fact that any defined object is truthy.

if (window.File) {
    console.log('your browser supports the File API');

The Logical Or

JavaScript’s logical or operator (||) does not necessarily yield true or false. It actually yields the left-side value if it is truthy, otherwise it yields the right-side value. Let’s look at what is really happening when you use || in an if statement.

if (41 === 'potato' || window.File) {
    console.log('reality is melting and the number 41 is now a potato, or your browser supports the File API');

The left-side value is false, which is of course falsey. So the logical or operator yields the right-side value. The right-side value is truthy. The if statement sees the truthy value and succeeds.

Null Coalescing

Alright, so that was technically boring. Here’s another example with a more interesting application.

var obj = incomingObj || {};

This is JavaScript’s practical way of doing null coalescing. If the left-side incomingObj is defined, then it is truthy, and so obj is set to it. Otherwise the right-side {} is returned, causing obj to be set as a new object.

You can even chain your logical or operators.

var obj = firstChoiceObj || secondChoiceObj || thirdChoiceObj || {};

The first defined object, reading left to right, is what obj is set to.

Hey, you reached the end!

Feel free to check out my other blog posts or subscribe to my RSS feed. You can also click a tag below to see related blog posts.