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

Short-Circuit Evaluation with ||

Learn how || stops at the first truthy value, enabling default value patterns.

Short-Circuit Evaluation with ||

You'll learn how the || operator stops evaluating as soon as it finds a truthy value, making it perfect for setting default values.

How || Short-Circuits

Remember that || returns the first truthy value it encounters, or the last value if none are truthy. Here's the key: JavaScript doesn't even look at the second operand if the first one is already truthy.

This behavior is called short-circuit evaluation. Think of it like a relay race where the first runner who succeeds wins immediately—there's no need to run the second leg.

let result = true || console.log("This never runs!");
// result is true, and nothing is printed

The console.log() never executes because true is truthy, so JavaScript stops there.

The Default Value Pattern

This makes || incredibly useful for providing fallback values:

let username = "" || "Guest";
// username is "Guest" because "" is falsy

let count = 0 || 10;
// count is 10 because 0 is falsy

let name = "Alice" || "Default";
// name is "Alice" because it's truthy

Watch Out for Falsy Values

Be careful when the first value could legitimately be 0, "", or false:

let score = 0 || 100;
// score is 100, but maybe you wanted 0!

If 0 is a valid value you want to keep, || isn't the right tool (though solutions exist that you'll learn later).

Key Takeaway: The || operator short-circuits at the first truthy value, making it a quick way to set defaults, but remember it treats all falsy values the same way.