CodeBlanks Logo Icon CodeBlanks

Truthy and falsy values

JavaScript course · Beginner · Lesson 97/133

Learn which values are considered false and which are true in a boolean context.

Falsy values

In JavaScript some values behave like false in a boolean context; these are called falsy. There are six in total: false, 0, "" (empty string), null, undefined and NaN.

Every other value behaves like true. For example if (0) does not run its block because 0 is falsy. But if ("0") does run because a non-empty string is truthy. It is important not to confuse an empty string with a filled one.

Boolean() and the if condition

You can see whether a value is truthy or falsy explicitly with Boolean(): Boolean("") gives false, Boolean("hello") gives true.

The if condition also converts the value to boolean automatically. That is why if (name) skips the block when name is an empty string. This is the shortest way to catch empty input from a user.

Exercise Show the boolean conversion

Define a function called showBoolean. It should take a value parameter. Inside, first convert the value to boolean with let result = Boolean(value); then write console.log(result).

Show example solution
function showBoolean(value) {
  let result = Boolean(value);
  console.log(result);
}

Exercise Test four values

The showBoolean function below is defined. Now call it with four values: showBoolean(0), showBoolean(""), showBoolean("0") and showBoolean([]). Put each call on its own line.

Show example solution
function showBoolean(value) {
  let result = Boolean(value);
  console.log(result);
}

showBoolean(0);
showBoolean("");
showBoolean("0");
showBoolean([]);

Test yourself

  1. Which is a falsy value?

    • "0"
    • "false"
    • []
    • 0
    Show answer

    0 — Correct. 0 is in the falsy list; the others are truthy.

  2. Convert explicitly to boolean

    let isOn = ____(0);
    console.log(isOn);
    Show answer
    let isOn = Boolean(0);
    console.log(isOn);
  3. Match the value to its kind

    0
    Number (falsy)
    "0"
    String (truthy)
    ""
    Empty string (falsy)
    []
    Empty array (truthy)

All lessons in Beginner