DEV Community

Cover image for Short-Circuit Evaluation in JavaScript: Boost Performance and Simplify Logic!
Geetansh Chahal
Geetansh Chahal

Posted on

Short-Circuit Evaluation in JavaScript: Boost Performance and Simplify Logic!

Have you ever wondered how ??, ||, and && work internally to determine the result they return? Is the result always correct? What’s the difference between them? No worries, buddy—let’s break it down and solve this peculiar mystery!🧐

Short-circuit evaluation in JavaScript refers to a programming concept where logical operators evaluate expressions from left to right and stop as soon as the result is determined.

Logical AND (&&):

It returns the first falsy value it encounters or the last value if all are truthy.

let x = 5;
let y = 0;

console.log(x && y);  // 0
console.log(x && true);  // true
Enter fullscreen mode Exit fullscreen mode

Logical OR (||):

It returns the first truthy value it encounters or the last value if all are falsy.

let a = null;
let b = "Hello";

console.log(a || b);  // Hello
console.log(a || false);  //false
Enter fullscreen mode Exit fullscreen mode

Nullish Coalescing Operator (??):

It’s used to provide a default value only when the left-hand operand is null or undefined.

let userName = null;
let result = 0 ?? 100;

console.log(result);  // 0
console.log(userName ?? "Guest")  // Guest
Enter fullscreen mode Exit fullscreen mode

Combined Usage:

We can use them together as well, but it is recommended to use parentheses to avoid confusion and undesired results.

let a = null;
let b = 0;
let c = 10;
let d= 20

let result = (a ?? b) || (c && d);
console.log(result);  // 20
Enter fullscreen mode Exit fullscreen mode

(a ?? b) → (null ?? 0) → 0 //since left is null
(c && d) → (10 && 20) → 20 //since left is truthy
(a ?? b) || (c && d) → ( 0 || 20) → 20 //since left is falsy

Merits:

  • Optimizes performance by skipping unnecessary evaluations.
  • Make the code cleaner and more readable.
  • Prevent runtime errors by avoiding operations on null or undefined values.

Demerits:

  • If a condition fails, it can be challenging to identify the issue during debugging.
  • Can confuse readers about the intent.
  • Can lead to unintended results

Best Practices:

  • Use it for simple logic.
  • Add comments to improve understanding of the logic for other coders.
  • Use ?? instead of || when dealing with null or undefined values to avoid overriding falsy values like 0 or "".

Short-circuit evaluation is not limited to JavaScript; it is widely used in many programming languages such as Python, Java, C/C++, Kotlin, Go, Swift, and more. However, the symbols and usage can vary slightly depending on the language's syntax and conventions.

If you like the post, react to it and share your views.
Connect on LinkedIn:- www.linkedin.com/in/geetansh-chahal-b7473b1b4/

Top comments (0)