0
What is the value of result and why ?
const func = function () { return 2009; } const result = 262 && func();
2 odpowiedzi
+ 2
2009, because all numerics values except 0 are considered equivalent to true (and zero equals false)...
So, the right handed side of the final expression is:
262 && func()
operator && is a logical and, so require boolean (true/false) values as arguments, so from left to right 262 is evaluated as true, and func() return 2009, wich is also equals to true.
But in js, and in other languages (such as python) the logical operator doesn't really cast the value to boolean... instead they evaluate temporarly their boolean equivalent, but return the value itself:
0 && 'test' == 0 // 0 is equals to false, so testing the other value don't make sense
42 && 'test' == 42 // 42 is true, so the other value is evaluated
42 && 0 == 0 // 42 is true, 0 is false, 0 is returned because it's the last value returned
almost the same with the or || operator:
0 || 'test' == 'test' // 0 is false, so the other value is evaluated and returned
42 || 'test' == 42 // 42 is true, so testing the other value doesn't make sense
42 || 0 == 42