Using || for Default Values
You'll learn: How to use the || operator to provide backup values when a variable might be falsy.
The Core Idea
Because || uses short-circuit evaluation, it returns the first truthy value it encounters. If the left side is falsy, JavaScript moves to the right side and returns that instead. This behavior makes || perfect for setting default values when you're not sure if a variable contains useful data.
Think of it like asking a friend for a pen: "Do you have a pen, or should I use mine?" If they don't have one (falsy), you automatically grab yours (the default).
How It Works in Practice
let userInput = "";
let message = userInput || "Hello, Guest!";
console.log(message); // "Hello, Guest!"
Since "" (empty string) is falsy, JavaScript skips it and uses "Hello, Guest!" instead.
let count = 0;
let displayCount = count || 10;
console.log(displayCount); // 10 (watch out — 0 is falsy!)
let username = "Alice";
let greeting = username || "Anonymous";
console.log(greeting); // "Alice"
Here, "Alice" is truthy, so that's what gets assigned—no need to look at the default.
Common Use Case
function greet(name) {
name = name || "Stranger";
return "Hello, " + name + "!";
}
console.log(greet("Bob")); // "Hello, Bob!"
console.log(greet("")); // "Hello, Stranger!"
console.log(greet()); // "Hello, Stranger!"
Be Careful with Zero and Empty Strings
Remember: 0, "", and false are all falsy. If those are valid values in your case, || will incorrectly replace them with the default.
Key Takeaway: Use || to provide fallback values by leveraging short-circuit evaluation—just remember it triggers on any falsy value, not just null or undefined.