Short Circuiting In JS

Short Circuiting In JS: Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about the Short Circuiting In JavaScript.

Short Circuiting In JS

Short-circuiting is a feature of JavaScript that allows you to stop the evaluation of an expression or a function call as soon as the result is known. This is done by using logical operators such as && (AND) and || (OR) in a way that makes use of their specific behavior.

The AND (&&) operator returns the first operand if it is falsy, otherwise it returns the second operand.

Code For AND (&&) operator In JavaScript

console.log(null && "hello");
console.log("hello" && "world");

Output

null

“world”

The OR (||) operator returns the first operand if it is truthy, otherwise it returns the second operand.

Code For OR (||) Operator In JavaScript

console.log(null || "hello");
console.log("hello" || "world");

Output

“hello”

“hello”

Short-circuiting can be used to assign a default value to a variable if it is undefined or null.

let x;
let y = x || "default value";
console.log(y);

Output

“default value”

This can also be useful to avoid making unnecessary function calls or calculations.

function getData() {
  if (!data) {
    return null;
  }
  // do something with data
}

let data = getData() || "default data";

In this example, the function call getData() is only executed if the variable data is not truthy, allowing you to avoid unnecessary function calls.

Conclusion

Short-circuiting behavior of these operators allow us to write more efficient and compact code and also helps in avoiding unnecessary computations.


If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Share on:

NK Coderz is a Computer Science Portal. Here We’re Proving DSA, Free Courses, Leetcode Solutions, Programming Languages, Latest Tech Updates, Blog Posting Etc.

Leave a Comment