DEV Community

Cover image for Short-Circuit Evaluation: Making Your Code More Concise
Mainul Hasan
Mainul Hasan

Posted on • Updated on • Originally published at javascript.plainenglish.io

Short-Circuit Evaluation: Making Your Code More Concise

In programming, writing clean and efficient code is an art that developers passionately pursue. One such technique in JavaScript, and many other languages, is the use of short-circuit evaluation.

This method not only improves the readability of your code but also optimizes its performance.

What is Short-Circuit Evaluation?

Short-circuit evaluation in programming languages is the act of skipping the evaluation of the rest of a logical expression as soon as the result is determined.

For instance, in a logical OR (||) operation, if the first operand is true, the overall result must be true, regardless of the value of the second operand. Thus, the second operand isn’t evaluated.

Short-Circuiting with OR (||)

Consider the following example:



let result = true || console.log("This won't be logged");


Enter fullscreen mode Exit fullscreen mode

Here, the console.log statement never executes because the first value (true) is sufficient to determine the overall result.

Short-Circuiting with AND (&&)

Similarly, if the first operand of a logical AND (&&) operation is false, the overall result must be false regardless of the value of the second operand.



let result = false && console.log("This won't be logged either");


Enter fullscreen mode Exit fullscreen mode

Applying Short-Circuit Evaluation in Practice

Short-circuit evaluation is not just a theoretical concept; it has practical applications that can simplify your code:

1 — Default values: Assigning a default value if a variable is undefined or null.



let name = user.name || "Guest";


Enter fullscreen mode Exit fullscreen mode

2 — Conditional function execution:



userIsLoggedIn && displayWelcomeMessage();


Enter fullscreen mode Exit fullscreen mode

3 — Optional chaining: An advanced feature in modern JavaScript, the optional chaining operator (?.) lets you access nested object properties without checking each layer for validity. It automatically returns undefined if the reference is nullish, streamlining code and preventing potential errors.



let userAge = user?.profile?.age || "Age not set";


Enter fullscreen mode Exit fullscreen mode

Beware of Unintended Side Effects

While short-circuiting can be powerful, it can lead to unexpected behavior if not used properly. One of the most common pitfalls is when relying on side effects in expressions.

Consider the following example:



let x = false;
let y = true;

function updateX() {
  x = true;
  return x;
}

if (y || updateX()) {
  console.log("This block will execute");
}
console.log(x);  // What will this output?


Enter fullscreen mode Exit fullscreen mode

In the code above, because y is true, the updateX() function will never execute due to short-circuiting. As a result, the value of x remains false.

If a developer is unaware of short-circuiting, they might assume that updateX() always executes and that x is set to true. However, due to short-circuiting, this isn't the case.

This example highlights the need for caution when using functions or expressions with side effects in logical operations. Make sure your code doesn’t unknowingly depend on these side effects for its subsequent operations.

Conclusion

Short-circuit evaluation is a powerful tool for developers. It helps write concise and efficient code, reducing redundancy and optimizing performance. By mastering this technique, you can improve the readability and efficiency of your code.

If you found this article useful or have more insights on the topic, feel free to connect with me on Twitter and LinkedIn. Let’s continue the conversation there!

Read Next...

Top comments (0)