DEV Community

Omar Albacha                 🔅
Omar Albacha 🔅

Posted on

Short-circuiting of logical operators and their return values

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

short-circuiting of logical operators

“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.

Top comments (0)