๐ŸŽ“ A1Learner
๐Ÿ”

JavaScript Booleans

A boolean is a value that is either true or false. Booleans answer yes-or-no questions inside a program.

Comparisons give booleans

Each comparison here answers with true or false.

let score = 80;
console.log(score === 80);
console.log(score > 100);
console.log(score < 100);

Converting with Boolean

Boolean turns a value into its true or false answer. The number 1 converts to true, and 0 converts to false.

console.log(Boolean(1));
console.log(Boolean(0));
console.log(Boolean("hi"));
console.log(Boolean(""));

A stored answer picks a value

A variable can store the answer of a comparison. The ternary operator then picks a value based on that answer.

let age = 20;
let isAdult = age >= 18;
console.log(isAdult);
let label = isAdult ? "adult" : "child";
console.log(label);

Example

let temperature = 30;
let isHot = temperature > 25;
console.log(isHot);
console.log(Boolean(temperature));
console.log(Boolean(0));
let message = isHot ? "Warm day" : "Cool day";
console.log(message);

Key points

  • Every boolean holds one of two values, true or false.
  • A comparison checks two values and produces a boolean.
  • The Boolean conversion turns a value into its true or false answer.
  • A truthy value converts to true, and a falsy value converts to false.
  • Only six values are falsy, and they are false, 0, an empty string, undefined, null, and NaN.
  • Every other value is truthy, including the text "0" and negative numbers.

In this example, the comparison temperature > 25 stores true in isHot. Boolean then converts 30 to true and 0 to false. The ternary operator uses isHot to pick the text "Warm day".

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

Which value is falsy?