Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is NaN a global variable in JavaScript?

Tags:

javascript

I've noticed that NaN is implemented as a global variable (window.NaN) whose value is NaN.
Why is this the case? Wouldn't it make more sense for it to be a reserved word that represents a value, like true, false, and null?

EDIT apparently this is in the spec, along with undefined and Infinity. WTF JavaScript?!

like image 935
Daniel Weiner Avatar asked May 04 '15 14:05

Daniel Weiner


People also ask

Why does JavaScript show NaN?

The special value NaN shows up in JavaScript when Math functions fail ( Math. sqrt(-37) ) or when a function trying to parse a number fails ( parseInt("No integers here") ). NaN then poisons all other math functions, leading to all other math operations resulting in NaN .

How do I fix NaN error in JavaScript?

In this article, we will convert the NaN to 0. Using isNaN() method: The isNan() method is used to check the given number is NaN or not. If isNaN() returns true for “number” then it assigns the value 0. Using || Operator: If “number” is any falsey value, it will be assigned to 0.

What is NaN in JavaScript?

In JavaScript, NaN is short for "Not-a-Number". In JavaScript, NaN is a number that is not a legal number. The Global NaN property is the same as the Number. Nan property.

What is NaN equal to in JavaScript?

NaN values are generated when arithmetic operations result in undefined or unrepresentable values. Such values do not necessarily represent overflow conditions. A NaN also results from attempted coercion to numeric values of non-numeric values for which no primitive numeric value is available.


1 Answers

It's not just implemented that way, it's specified that way:

15.1.1 Value Properties of the Global Object

15.1.1.1 NaN

The value of NaN is NaN (see 8.5). This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

15.1.1.2 Infinity

The value of Infinity is +∞ (see 8.5). This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

15.1.1.3 undefined

The value of undefined is undefined (see 8.1). This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

(The global object is the window object on browsers.) An implementation that doesn't do it is violating the spec. :-)

As for why: The spec doesn't seem to say why, so unless someone can find a quote from Brendan Eich explaining his reasoning... :-) I will just speculate mention that making them globals is somewhat less limiting: You can have a local Infinity variable in your code meaning something else if you don't need access to the global one. You couldn't do that if it were a reserved word. Mind you, it opens the door to trouble as well, so...

like image 55
T.J. Crowder Avatar answered Sep 21 '22 17:09

T.J. Crowder