Skip to content
Logical Operators (and, or)
step 1/3

Reading — step 1 of 3

Short-Circuit Evaluation

~2 min readControl Flow & Functions

Logical Operators (and, or)

The logical operators and and or are not ordinary binary operators. They use short-circuit evaluation — the right operand is only evaluated if necessary.

Short-Circuit Semantics

and: If the left operand is falsy, return it immediately without evaluating the right. Otherwise, return the right operand.

false and sideEffect()   // returns false, sideEffect() never called
true and "yes"           // returns "yes"

or: If the left operand is truthy, return it immediately. Otherwise, return the right operand.

"hello" or sideEffect()  // returns "hello", sideEffect() never called
nil or "default"          // returns "default"

Returning Values, Not Booleans

Notice that and and or return one of their operands, not true/false. This enables idiomatic patterns:

var name = user or "anonymous";   // default value
var valid = x and x.isValid();    // guard clause

Python works the same way: "" or "default" returns "default". Lua also returns operands rather than booleans.

Why Not Regular Binary Operators?

Normal binary operators evaluate both operands before applying the operator. But false and crashTheUniverse() must NOT crash — the right side must not execute. This is why and/or need special handling in both the AST and the interpreter.

In the AST, we use a separate Logical node type rather than Binary:

Logical {
    left:  Expression
    op:    AND or OR
    right: Expression
}

Precedence

or has lower precedence than and, so:

a or b and c  →  a or (b and c)

Both have lower precedence than equality and comparison:

x == 1 or y == 2  →  (x == 1) or (y == 2)

Implementation

evaluateLogical(expr):
    left = evaluate(expr.left)
    if expr.op == OR:
        if isTruthy(left): return left    // short-circuit
    else:  // AND
        if !isTruthy(left): return left   // short-circuit
    return evaluate(expr.right)           // only if needed

Your Task

Implement and and or with short-circuit evaluation, correct precedence, and value-returning semantics.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…