+ 3
JS Question
var x = 2; var y = 4; if((y > x || y++ >= 4) && ++y === 5){ x = 1; } else{ x = 4; } console.log(x); // 1 console.log(y); // 5 In this Task, why final value of y isnt 6? Doesnt y increment by 1 after first comparison, since it is true and then increments again by 1 in second comparison, resulting in y = 6 and therefore x = 4
3 odpowiedzi
+ 4
When either operand of logical OR (||) is truthy-value it evaluates to that truthy-value.
In short it returns first truthy operand.
Thruthy values:
https://developer.mozilla.org/en-US/docs/Glossary/Truthy
If first operand of || is truthy second operand is not checked.
This is known as "Short Circuit Evaluation". In your case JS doesn't evaluate second operand y++ >= 4 as y>x is true.
https://codeburst.io/javascript-what-is-short-circuit-evaluation-ff22b2f5608c
example:
console.log({ } || [ ]); // object literal is truthy. || returns { }
console.log("" || "o"); // empty string is falsy. returns next value "o" which is truthy.
console.log(false || null || true || {}); //returns true, the first truthy operand in expression.
This can be useful when you want to use some default value.
let name = prompt() || "Anonymous";
alert(name);
if you press cancel prompt returns null (falsy) in that case - || returns "Anonymous".
+ 4
Thanks Omkar for your great explanation and for the sources, It really helped me see the bigger picture. Also thanks lpang for the sources.
+ 3
What we see here is an effect of short circuit evaluation. You will find answer plus explanations in the following
https://en.m.wikipedia.org/wiki/Short-circuit_evaluation
https://www.tutorialspoint.com/short-circuit-evaluation-in-javascript