Short circuiting in || && ?? operators, Javascript

·

2 min read

Table of contents

No heading

No headings in the article.

blog2.jpg Image Source:Google

You heard of OR logic gate? Well || operator is like that only. If any of the two inputs is true (which are being compared at a specific point in time) it will short circuit there and won't execute further.

true||console.log("execute");
//output true
false||console.log("execute");
//output execute

As you can see if first is true second won't execute and if first is false it have to check further as second might be true.

Now comes && which is like AND logic gate

true&&console.log("execute");
//output execute
false&&console.log("execute");
//output false

In this case only true && true will evaluate to true ,so if the first input is false ,it will short circuit there and won't execute any further.

You may have a question what values are considered as false.

False values => false,0,null,undefined,""(empty string),NaN [],{} are NOT false An empty array or object is simply pointing to an object or array in memory so it stores the address and is not false.

Now comes ?? known as Nullish coalescing operator .

well it also short circuits but at first defined value(which is not null/undefined)

let input="";
input||"name";
//output name
input??"name";
//output ""

As input is defined so ?? short circuits at input as it is the first not null or undefined while || checks for first true value.

An that's short circuit which implies shortest path for circuit to complete. Thank you for reading :)