Lesson 18 +10 XP

JavaScript Booleans

JavaScript Booleans

A boolean is a value that is either true or false. They drive all decisions in JavaScript.

The two values

let isDone = true;
let isReady = false;

Booleans from comparisons

Most booleans come from comparison results:

let isAdult = age >= 18; // true or false

Truthy and falsy

JavaScript converts values to booleans automatically in conditions. Falsy values act like false:

  • false
  • 0
  • "" (empty string)
  • null
  • undefined
  • NaN

Everything else is truthy (acts like true), including non-empty strings and any non-zero number.

Example

if ("hello") {
  console.log("This always runs"); // "hello" is truthy
}
if (0) {
  console.log("Never runs"); // 0 is falsy
}

Boolean() function

Boolean(value) converts any value to true or false:

Boolean(0);     // false
Boolean("hi");  // true

TL;DR

  • Booleans are true or false.
  • Comparisons produce booleans.
  • Falsy values: false, 0, "", null, undefined, NaN.
  • Everything else is truthy.