2

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);
HH.
  • 197
  • 3
  • 17
  • 1
    Possible duplicate of [Two pipe symbols (OR) in this Javascript line](http://stackoverflow.com/questions/10358823/two-pipe-symbols-or-in-this-javascript-line) – J0B Jan 10 '16 at 14:15
  • Any non-zero number is considered truthy and will return `true` when converted to a boolean. – Nick Zuber Jan 10 '16 at 14:19
  • fyi: sometimes it's handy to just do `if ( [10,11].indexOf(number) !== -1 )` – adeneo Jan 10 '16 at 14:19
  • Possible duplicate of [What does the construct x = x || y mean?](http://stackoverflow.com/questions/2802055/what-does-the-construct-x-x-y-mean) – Michał Perłakowski Jan 16 '16 at 02:58

3 Answers3

6

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

Community
  • 1
  • 1
J0B
  • 1,648
  • 1
  • 12
  • 24
  • I like this answer because you actually address *why* the conditional expression is returning 11 – Nick Zuber Jan 10 '16 at 14:21
  • I think he knows that, the problem was that he thought `number === 10 || number === 11` would be the same as `number === 10 || 11` – CoderPi Jan 10 '16 at 14:26
5

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)
CoderPi
  • 12,985
  • 4
  • 34
  • 62
0

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

gurvinder372
  • 66,980
  • 10
  • 72
  • 94