HH.
HH.

Reputation: 197

Logical operator || returns number instead of boolean value

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

Answers (3)

CoderPi
CoderPi

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 here

Now let's have a closer look atnumber === 10 || 11 :

  • number === 10 will be true if number is of type number and equal to 10
  • if the first was false, it will evaluate the boolean value of the next statement: 11 (wich is accepted as true, for beeing a number not equal to 0)

Upvotes: 5

gurvinder372
gurvinder372

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

J0B
J0B

Reputation: 1648

from this question.

(expr1 || expr2)

"Returns expr1 if it can be converted to true; otherwise, returns expr2."

source

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

Related Questions