-1

I've noticed when I have:

console.log(( NaN||9) );  // returns 9

Why is this so? Why, when you evaluate - put parentheses around - NaN OR 9, it chooses the 9? It works with 0, -3, "f". Can someone please tell me what is going on in the background to cause this outcome??

Huckleberry
  • 21
  • 1
  • 8
  • 2
    Did you read the documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators? NaN is falsey – Andrew Li Dec 14 '17 at 00:18
  • `-3||9` should return -3 and `"f"||9` should return "f". It's a matter of whether a value is truthy or falsey, which has been explained in many places far better than I can – CrayonViolent Dec 14 '17 at 00:19

2 Answers2

2

In JavaScript, NaN is a "falsy" value. The || operator evaluates to either its first argument (if that is "truthy") or else to the second argument (if the first argument is "falsy"). Hence NaN || 9 evaluates to 9.

From the docs for logical operators:

Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.

and for || specifically:

Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

Short answer, because NaN is falsy.

Here's a list of falsy values in javascript.

The logical OR opertator || in javascript can be tricky, but once you know how it works its both straightforward and very handy. If it's left side is falsy, then it's result will be whatever it's right side is (in your case, the number 9).

CRice
  • 29,968
  • 4
  • 57
  • 70