Short circuiting is an unique way of logical operators (&& and ||) handling the operands of different types.
Logical operators are generally considered as boolean operators. However, they handle the operands of different types by converting them to Boolean primitives.
The process of conversion happens in the following way,
- The evaluation of expression starts from left to right
- They will convert the value on their left side to Boolean type.
- Then they decide what to return, either _original left side value or _original right side value based on the operator.
- If the operator is ||, it will return the left side value if it can be converted to true else it returns right side value. For example:
var testFunction = function(){
console.log("true");
return true;
}
var testFunction2 = function(){
console.log("false");
return false;
}
var result = testFunction() || testFunction2();
// prints true in console and never executes the testFunction2()
// result -> true
result = testFunction2() || testFunction();
// prints both false and true in console since the left side expression returns false
// result -> true
In the above example, the testFunction2() never gets evaluated because
- If || operator encounters truthy expression on its left side , then it doesn't care about right side expression and hence the right side expression never gets evaluated.
- If || operator encounters falsy expression on its left side then it evaluates the right side expression and returns the latter
The behaviour is similar with the && operator but the other way around.
- Here if it encounters the truthy expression on its left side then it returns the right side value
- If the left side expression turns out to be falsy it returns the left side value and doesn't care about the right side expression
var testFunction = function(){
console.log("true");
return true;
}
var testFunction2 = function(){
console.log("false");
return false;
}
var result = testFunction() && testFunction2();
// prints true and false in console
// result -> false
result = testFunction2() && testFunction();
//prints false in console and doesnot evaluate testFunction()
//result -> false
Also remember that there are few expressions that are always falsy(converted to false)
- null
- undefined
- NaN
- empty string('',"",``)
If you are still here reading the post, then kudos to you.You have successfully reached the end of post. But before leaving, if you closely observe the concept of short circuiting, you can see resemblance with the if-else conditionals. My next post is on the usage of short circuit for fallback to default values and replacing the if-else conditionals. Hope you enjoyed the post. Feel free to post your questions and suggestions
Top comments (0)