Course contentsShow
← JavaScript
Lesson 215 of 2,7236. Booleans and ConditionalsFree lesson

The || (OR) Operator

Understand how || returns the first truthy value or the last value if all are falsy.

The || (OR) Operator

You'll learn how the OR operator returns values, not just true or false.

How || Works

You already know && from the previous lesson. The || (OR) operator works similarly but in reverse: it returns the first truthy value it encounters. If all values are falsy, it returns the last value.

Think of || like a picky eater at a buffet: it grabs the first thing that looks good (truthy). If nothing looks good (all falsy), it reluctantly takes whatever is last.

The Evaluation Pattern

let result = value1 || value2;

JavaScript evaluates left to right:

  • If value1 is truthy → returns value1 (stops immediately)
  • If value1 is falsy → returns value2 (doesn't matter if it's truthy or falsy)

Examples

console.log("hello" || "world");     // "hello" (first truthy)
console.log(0 || 42);                // 42 (0 is falsy)
console.log(null || "default");      // "default" (null is falsy)
console.log("" || false || "yes");   // "yes" (first two are falsy)
console.log(false || 0 || null);     // null (all falsy, returns last)

Common Use Case: Default Values

Before modern features existed, developers used || for fallback values:

let userInput = "";
let name = userInput || "Guest";
console.log(name);  // "Guest"

If userInput is empty (falsy), name gets the default value "Guest".

Important: It Returns the Actual Value

Unlike comparison operators that return true or false, || returns one of the original values:

console.log(5 || 10);  // 5 (not true!)

Key Takeaway: The || operator returns the first truthy value it finds, or the last value if all are falsy — it doesn't necessarily return a boolean.