Javascript - Short-circuit evaluation
Code Life
By Pierre Marsaa
What is Short-Circuit Evaluation?
When JavaScript evaluates logical operators like && and ||, it doesn't always need to check both sides to know the result. This is called short-circuit evaluation.
Here's how it works:
With && (AND):
- If the left side is falsy, JavaScript knows the whole expression will be false
- So it stops and never evaluates the right side
With || (OR):
- If the left side is truthy, JavaScript knows the whole expression will be true
- So it stops and never evaluates the right side
Let's see this in action! Run the code below and watch which messages appear:
Example with &&:
The first line won't print because the left side is false, so JavaScript doesn't need to evaluate the right side because AND is false.
↗️
Loading editor...
↶
↷
Example with ||:
The first line won't print because the left side is true, so JavaScript doesn't need to check the right side because OR is true.
↗️
Loading editor...
↶
↷
Verify