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 Answers
+ 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