Short-Circuit Evaluation Explained: How AND and OR Can Skip Work in Your Code

Learn how short-circuit evaluation works with AND and OR, why it prevents errors, how to use it for defaults and guards, and the pitfalls to avoid.

Share on Linkedin Share on WhatsApp

Estimated reading time: 7 minutes

Article image Short-Circuit Evaluation Explained: How AND and OR Can Skip Work in Your Code

Look at this line of code: if user is not None and user.is_active:. If user is None, why doesn’t the program crash when it tries to read user.is_active? The answer is a small but powerful rule that almost every programming language follows: short-circuit evaluation. Once you understand it, you will write safer conditions, shorter code, and avoid a few classic bugs.

In this article, you will learn what short-circuit evaluation is, how it works with the AND and OR operators, where it is useful in everyday code, and the mistakes that catch beginners off guard.

What is short-circuit evaluation?

Logical expressions are evaluated from left to right. Short-circuit evaluation means that the program stops evaluating as soon as the final result is already known. The remaining parts of the expression are simply skipped.

This is possible because of how AND and OR work in Boolean logic:

  • AND is only true if both sides are true. If the left side is false, the whole expression must be false, no matter what is on the right.
  • OR is true if at least one side is true. If the left side is true, the whole expression must be true, no matter what is on the right.
ExpressionLeft sideIs the right side evaluated?Result
A AND BfalseNofalse
A AND BtrueYesdepends on B
A OR BtrueNotrue
A OR BfalseYesdepends on B

The operators look different from language to language — and/or in Python, &&/|| in C, Java, JavaScript and C# — but the idea is the same.

Seeing it in action

A simple way to prove that the right side is skipped is to put a function with a visible side effect there:

def check():
    print("check() was called")
    return True

print(False and check())   # prints: False  (check() never runs)
print(True or check())     # prints: True   (check() never runs)
print(True and check())    # prints the message, then True

In the first two lines, the message never appears. The interpreter already knew the answer after reading the left side, so it never called check().

Use case 1: guard conditions that prevent errors

The most important use of short-circuiting is protecting the right side of an expression from running when it would fail. The left side acts as a “guard”:

// JavaScript
if (user !== null && user.isActive) { ... }

// Avoiding division by zero
if (count > 0 && total / count > 10) { ... }

// Avoiding an index out of range (Python)
if len(items) > 0 and items[0] == "start":
    ...

Notice that the order matters. If you swap the two sides — user.isActive && user !== null — the program tries to read a property of null before checking it, and crashes. Always put the safety check first.

Use case 2: skipping expensive work

Because the right side may not run at all, you can place cheap checks first and slow checks last. For example, checking a local variable before calling a database or an external API:

if is_logged_in and has_permission_in_database(user_id):
    show_admin_panel()

If the user isn’t logged in, the database is never queried. In code that runs thousands of times, ordering conditions from cheapest to most expensive can make a noticeable difference.

Use case 3: default values

In some languages, including Python and JavaScript, and/or (or &&/||) don’t return just true or false. They return the last value they evaluated. That makes the OR operator a popular shortcut for defaults:

# Python
name = user_input or "Guest"

// JavaScript
const port = config.port || 3000;

If the left value is “falsy” (empty, zero, None/null, etc.), the expression returns the right value. Be careful, though: the number 0 and the empty string are also falsy. If 0 is a valid port or quantity in your program, || will wrongly replace it. Modern JavaScript offers the nullish coalescing operator ??, which only falls back when the value is null or undefined:

const quantity = 0;
console.log(quantity || 10);  // 10  (probably not what you want)
console.log(quantity ?? 10);  // 0   (keeps the valid zero)

The ?? operator also short-circuits: the right side is only evaluated when needed.

Short-circuit vs. non-short-circuit operators

Several languages also have operators that look similar but always evaluate both sides. In Java and C#, for instance, & and | can be used with Boolean values, and they do not short-circuit. In C and many other languages, & and | are bitwise operators that work on the individual bits of integers.

OperatorShort-circuits?Typical use
&&, andYesLogical conditions
||, orYesLogical conditions, defaults
?? (JavaScript, C#)YesDefaults for null/undefined
&, |NoBitwise operations, or Boolean logic where both sides must run

Typing & when you meant && is a common typo. In some languages it may still compile, but your guard condition stops protecting you.

Common pitfalls

  • Hiding important side effects on the right. Code like isValid && saveToDatabase() works, but it’s easy to miss that the save might never happen. For actions (not checks), an explicit if is usually clearer.
  • Wrong order of conditions. The guard must come before the risky expression.
  • Using || for defaults when 0 or “” are valid. Prefer ?? or an explicit check.
  • Overly clever one-liners. Chaining many and/or operators to replace an if/else makes code harder to read. Readability usually wins.

A quick mental checklist

  1. Read the condition from left to right.
  2. For AND: as soon as something is false, stop — the answer is false.
  3. For OR: as soon as something is true, stop — the answer is true.
  4. Ask yourself: “Could the right side crash or be slow?” If so, make sure the left side protects it.

Conclusion

Short-circuit evaluation is one of those fundamentals that quietly shows up in almost every program. It lets you write guard conditions that avoid crashes, skip unnecessary work, and set default values in a single line — as long as you keep the order of conditions and the meaning of “falsy” values in mind.

If you want to strengthen your foundations in logic, conditions and algorithms, explore the free Programming Fundamentals courses on Cursa and practice these ideas in the language of your choice.

Blog

Related articles

Read more about Programming Fundamentals