Reputation: 197
I attached an example with two if conditions. The first if condition works as expected. The second if condition returns 11, but why? I know that the second if condition is wrong, but I would like to understand why Javascript returns in that case 11.
function exception(number) {
// if(number === 10 || number === 11) { // Working as expected
if(number === 10 || 11) { // Why 11?
console.log(number);
}
}
function loop(f) {
for (i = 0; i <= 100; i++) {
f(i);
}
}
loop(exception);
Upvotes: 2
Views: 624
Reputation: 13211
Some Information about what you where trying to achieve:
number === 10 || number === 11
is the same as (number === 10) || (number === 11)
number === 10 || 11
is the same as (number === 10) || (11)
it does not compare 11
to number
hereNow let's have a closer look atnumber === 10 || 11
:
number === 10
will be true
if number is of type number and equal to 10 11
(wich is accepted as true, for beeing a number not equal to 0)Upvotes: 5
Reputation: 68393
because Boolean(11)
is true
(try on your console)
so even if first condition is not true (if the number is not 10), then second condition will be true always
Upvotes: 0
Reputation: 1648
from this question.
(expr1 || expr2)
"Returns expr1 if it can be converted to true; otherwise, returns expr2."
So when expr1
is (or evaluates to) one of these 0,"",false,null,undefined,NaN
, then expr2
is returned, otherwise expr1
is returned
Upvotes: 6