Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does NaN = !NaN return true?

NaN is one of those vestigial implementations of questionable origins, but for the most part I get it. However, I typed this into a Node prompt today and couldn't really make sense of it...

NaN = !NaN
> true

Is this simply returning the evaluated result of !NaN? This makes sense, but I'm surprised that there's not an error when attempting to assign NaN to another value.

Note: this question is about this specific syntax structure; there are a lot of questions related to NaN and isNaN out there but I couldn't find an answer after googling. Thanks to Ori Drori for the best answer thus far.

console.log(NaN = !NaN);
like image 920
newswim Avatar asked Dec 02 '25 13:12

newswim


2 Answers

You are assigning true to NaN instead of comparing NaN to !NaN using === or ==, so the operation returns the assigned value -> true. Javascript ignores this assignment silently because NaN is read only.

console.log(NaN = true);

// NaN hasn't changed
console.log(NaN);

If you'll add use strict to your code, JS will throw a read only error instead:

'use strict';
NaN = true;
like image 157
Ori Drori Avatar answered Dec 05 '25 03:12

Ori Drori


= is the asignment operator. == and === are comparison operators.

NaN == !NaN
false
NaN === !NaN
false

Perhaps more surprisingly:

NaN  == NaN
false
NaN  === NaN
false

For more about NaN: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/NaN

like image 37
Eterm Avatar answered Dec 05 '25 02:12

Eterm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!