0

Why does this output 4? I'm having a bit of trouble distinguishing between the OR (| | ) and the Logical OR (||).

let a; let b = null; let c = 4; let d = 'five'; let e = a || b || c || d; alert(e); //I've tried Google. Didn't help.

3rd Mar 2018, 12:26 PM
Briaה‎
3 Réponses
+ 2
The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages. The Logical OR operator (||) returns the value of its second operand, if the first one is falsy, otherwise the value of the first operand is returned. For example: "foo" || "bar"; // returns "foo" false || "bar"; // returns "bar" Falsy values are those who coerce to false when used in boolean context, and they are 0, null, undefined, an empty string, NaN and of course false. So in your case ,a || b returns false , so value of e becomes value of c (which is 4 ,first true value)
3rd Mar 2018, 12:38 PM
Manorama
Manorama - avatar
+ 1
Thank you Manorama!
3rd Mar 2018, 12:58 PM
Briaה‎
+ 1
welcome ...
3rd Mar 2018, 1:00 PM
Manorama
Manorama - avatar