Booleans in JavaScript

Introduction

Booleans (true and false) express yes/no decisions—login allowed, feature enabled, form valid. They power if statements, loops, and logical expressions. This chapter shows how booleans are created, combined, and used without hidden coercion traps.

Prerequisites

Boolean Literals

javascript
// Direct true/false values
const isLoggedIn = true;
const hasError = false;
 
console.log(isLoggedIn, hasError);

Booleans from Comparisons

Comparisons produce boolean results:

javascript
// Comparison expressions
const age = 20;
const canVote = age >= 18;
const isTeen = age >= 13 && age <= 19;
 
console.log(canVote, isTeen);

Use === and !== for equality (covered in operators).

Truthy and Falsy Values

In conditions, non-boolean values coerce to boolean:

Falsy values:

  • false, 0, -0, 0n, "", null, undefined, NaN

Everything else is truthy (including "0" and "false" strings).

javascript
// Falsy and truthy in if
const name = "";
 
if (name) {
  console.log("Has name");
} else {
  console.log("Name missing");
}

Warning

Relying on truthiness is convenient but can hide bugs (0 is valid data). Prefer explicit comparisons when 0 or "" are meaningful values.

Logical Operators

Combine boolean expressions:

OperatorMeaning
&&AND (short-circuit)
||OR (short-circuit)
!NOT
javascript
// Logical combinations
const hasTicket = true;
const age = 17;
const allowed = hasTicket && age >= 18;
 
console.log(allowed);
 
if (!allowed) {
  console.log("Entry denied");
}

Short-circuit behavior:

javascript
// && stops at first falsy; || stops at first truthy
const user = null;
const displayName = user && user.name;
console.log(displayName);

Modern alternative for defaults: ?? in operators.

Boolean Conversion

javascript
// Explicit Boolean()
const count = 0;
console.log(Boolean(count));
console.log(!!count);

!!value is a common idiom to force true/false.

Mini Example: Form Validation Flags

javascript
// Simple validation flags before submit
const email = "user@example.com";
const password = "short";
 
const emailOk = email.includes("@");
const passwordOk = password.length >= 8;
const formValid = emailOk && passwordOk;
 
console.log({ emailOk, passwordOk, formValid });

FAQ

Should I use == or ===?

Prefer === almost always. == performs type coercion and causes subtle bugs.

Is if (flag === true) redundant?

Usually yes—if (flag) is idiomatic when flag is already boolean.

Why is "false" truthy?

It is a non-empty string. Only empty string "" is falsy among strings.

What comes next?

Null and undefined, then type conversion.