QamoosTech
Programming FundamentalsLanguage basicsIntermediatePythonJavaScript

Short-Circuit Evaluation

Pronunciationshort-SIR-kit ih-val-yoo-AY-shun

Definition

Short-circuit evaluation means and and or stop as soon as the result is known, so the rest of the expression is never evaluated.

Where you hear it

In code reviews about safe checks such as user and user.name, and in explanations of default values written with or.

Examples

  • The second check never runs when the first one is false.
  • We rely on short-circuiting to avoid reading a missing attribute.
  • In user and token is None, the second check is skipped when there is no user.

Common mistake

Putting code with side effects in the second part of and / or and expecting it to always run.

Don't confuse with

A bitwise operator such as &, which always evaluates both sides.

Say it at work

  • In a meeting or chatOrder the conditions so the cheap check runs first and short-circuits.
  • In an email or ticketBecause of short-circuiting, this never touches the database when the flag is off.