CuteMachine

Falsy Values In JavaScript

Falsy values are values that convert to the boolean value false. There are seven falsy values in JavaScript.

false
undefined
null
""
NaN
0
-0

All other values will convert to true. Numbers, Objects, really any other value than the seven falsy values above convert to true. Let's look at some examples.

5 ? 'truthy' : 'falsy';        // truthy
"hello" ? 'truthy' : 'falsy'   // truthy
true ? 'truthy' : 'falsy'      // truthy

false ? 'truthy' : 'falsy'     // falsy
undefined ? 'truthy' : 'falsy' // falsy
null ? 'truthy' : 'falsy'      // falsy

We usually test if a particular condition is met with the if statement. In the above example, we use the ternary operator, which also converts an expression to a boolean value.

Imagine you have a function foo() that expects an object as an argument. The function will call a method doSomething() on the passed object. What happens when you forget to pass the object or pass null or undefined?

(Warning: the example is contrived, you usually would use argument defaults or optional chaining to guard the call.)

const foo = (o) => {
  return o.doSomething()
}

foo()    // TypeError

You will get an error. It is a good idea to make your function safer and test whether the object has been passed.

const foo = (o) => {
  if (o) {
    return o.doSomething()
  }
}

foo()    // no error

Because o is undefined, it will convert to false. Undefined is a falsy value in JavaScript.

Posted on CuteMachine.

Jo's Profile ImageWritten by Jo who lives and works in Frankfurt building digital doodah. Stalk him on Twitter.

TOS • Privacy • Disclaimer