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.
3 Antworten
+ 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)
+ 1
Thank you Manorama!
+ 1
welcome ...