Course contentsShow
← Computer Science
Lesson 159 of 2,8724. Introduction to ProgrammingFree lesson

Short-Circuit Evaluation

How logical operators evaluate operands lazily to optimize performance and avoid errors.

Short-Circuit Evaluation

What you'll learn: How programming languages can skip unnecessary checks in logical expressions to save time and prevent errors.

The Core Idea

When you connect conditions with logical operators like AND (&&) or OR (||), the computer doesn't always need to check both sides. Short-circuit evaluation means the language stops checking as soon as it knows the final answer.

Think of it like asking two friends if they want pizza. With AND: if the first friend says "no," you already know the answer is no—you don't need to ask the second friend. With OR: if the first friend says "yes," you're done—at least one person wants pizza, so you don't need to ask the other.

How It Works

AND (&&): If the left side is false, the whole expression must be false, so the right side never runs.

(x > 0) && (y / x > 5)

If x is 0 or negative, the first check fails and the division y / x never happens—preventing a division-by-zero error!

OR (||): If the left side is true, the whole expression must be true, so the right side never runs.

(age >= 18) || (hasParentalConsent == true)

If age >= 18 is true, we don't bother checking parental consent.

Why It Matters

Short-circuit evaluation gives you two benefits:

  1. Performance: Skip unnecessary work
  2. Safety: Avoid operations that might cause errors (like dividing by zero or accessing invalid data)

Key Takeaway: Short-circuit evaluation stops checking logical conditions as soon as the final result is known, making your code both faster and safer.