Using && for Conditional Execution
You'll learn how to use the && operator as a shorthand way to run code only when a condition is true.
The Core Idea
You already know that && short-circuits: if the left side is falsy, it stops and returns that value without evaluating the right side. This behavior makes && useful as a compact alternative to simple if statements.
When the left side is truthy, JavaScript evaluates and returns the right side. You can put any expression on the right—including function calls or assignments—and it will only execute if the left condition passes.
Syntax Pattern
condition && doSomething();
This is equivalent to:
if (condition) {
doSomething();
}
Examples in Action
let score = 100;
let bonus = 10;
// Traditional if statement
if (score >= 100) {
bonus = bonus + 5;
}
// Using && for conditional execution
score >= 100 && (bonus = bonus + 5);
console.log(bonus); // 15
let user = "Alice";
let greeting = "";
// Only set greeting if user exists (is truthy)
user && (greeting = "Hello, " + user + "!");
console.log(greeting); // "Hello, Alice!"
When to Use This Pattern
This technique works best for simple, single-statement conditions. It makes code more compact but can reduce readability if overused. For complex logic or multiple statements, stick with traditional if blocks.
Key Takeaway: The && operator can execute code conditionally—the right side only runs if the left side is truthy, providing a concise alternative to simple if statements.