truthy and falsy in JavaScript

on in Methods, Events and Scopes
Last modified on

In JavaScript, any variable can be used in a logical context, such as the condition of an if statement or loop. Conditional expressions can be quite complex, but should ultimately evaluate to a single Boolean value. If the result of a conditional expression is not a Boolean, the JavaScript interpreter will automatically coerce the value to a Boolean. Unfortunately, many values do not map to distinctly true or false values. Because of this, the coerced Boolean values are often informally referred to as truthy or falsy ― approximations of true and false based on JavaScript’s coercion rules. The possible falsy values are listed below.

  • The Boolean value false
  • undefined
  • null
  • The empty string
  • The numeric values – 0 and 0
  • The NaN value

In the following example, the condition of each if statement contains a falsy value. Therefore, none of the “if” statement bodies are executed.

if (false) {
    // not executed
}

if (undefined) {
    // not executed
}

if (null) {
    // not executed
}

if ("") {
    // not executed
}

if (0) {
    // not executed
}

if (NaN) {
    // not executed
}

Any value that is not included in the list of falsy values is considered to be truthy. This includes non-null objects, non-zero numbers, and non-empty strings. String representations of falsy values such as "false", "0", and "null" fall into the category of truthy values. Empty objects and arrays are not null, and therefore are truthy as well. The following example contains several if statements whose conditions evaluate to true.

if (true) {
    // this is executed
}

if ({}) {
    // this is executed
}

if ([]) {
    // this is executed
}

if ("false") {
    // this is executed
}

if (3) {
    // this is executed
}

if (" ") {
    // this is executed
    // the string contains a space, so it is not the empty string
}

Related posts