Short-circuiting of logical operators and their return values
Omar Albacha đź”…
Posted on April 28, 2022
Im sharing my visual thinking and notes from the first chapter of Eloquent JavaScript going through the short-circuiting of logical operators ||
and &&
. This can be useful when thinking about a value you want to return conditionally and logically
“Another important property of these two operators (||
and &&
) is that the part to their right is evaluated only when necessary. In the case of true || X
, no matter what X
 is—even if it’s a piece of program that does something terrible—the result will be true
, and X
 is never evaluated. The same goes for false && X
, which is false
and will ignore X
. This is called short-circuit evaluation.”
Two-bullet summary of this is:
- When using
||
, we are looking for a true left side to return it otherwise we return the right side - When using
&&
, we are looking for a false left to return it otherwise we return the right side.
Posted on April 28, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 24, 2024
November 22, 2024