Short Circuiting in JS
Every time you solve the JS output question, you will definitely find the output unexpected. So let's learn a concept. You will definitely be amazed or will fall in love with JavaScript.
Goal: My main goal to provide you crisp content so that you donot need to waste your lot of time in reading many articles.
In this article, you will learn about a important concept for solving JS output questions and to understand how JavaScript works.?
In JavaScript, an expression is evaluated from left to right until it is confirmed that the result of remaining conditions will not going to affect the evaluated result.
Why it is named as short-ciruiting ?
Because while evaluating the expression from left to right, If result become clear, it short-circuit the expression and return the result.
Seems cool ?
With this property, Short Circuit evaluation avoid unnecessary work and leads to effective processing.
There are only two types of short circuits ---
1) AND (&&) Short Circuit -
The expression will be evaluated until we get the one false result, because the result will always be false(It short circuits and false is returned).
领英推荐
console.log( false && true ); // false -> from 1st
console.log( false && true && true ); // false -> just after 1st
console.log( true && true && true ); // true -> all evaluated
2) OR ( || ) Short Circuit -
The expression will be evaluated until we get one true result, because result will be true.
console.log( false || true ); // true -> from 2nd
console.log( true || false ) ; // true -> from 1st
console.log( true || false || false ); // true -> from 1st
console.log( false || true || true || false ); // true -> from 2nd
console.log( false || false ); // false -> all evaluated
Let's see some mixed examples ---
console.log(false && true || false || true ); // true ---> all evaluated
console.log( (true && false) || (true || false) ); -> see next line to understand
(true(all evauated) || true (from 1st) ) -> see next step
true // from 1st
Hope, It is enough to understand this concept.
JavaScript ??
Hurray! You have understood this concept.
STAY TUNED, FOR UPCOMING ARTICLES
HAPPY CODING!
HAPPY DEVELOPEMENT!
#FOLLOW ME FOR SUCH AMAZING CRISP CONTENT