Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: what is NaN, Object or primitive?

Tags:

javascript

nan

what is NaN, Object or primitive?

NaN - Not a Number

like image 853
DuduAlul Avatar asked May 08 '12 12:05

DuduAlul


People also ask

Is NaN an object in JavaScript?

Description. NaN is a property of the global object. In other words, it is a variable in global scope. The initial value of NaN is Not-A-Number — the same as the value of Number.

Is object a primitive in JavaScript?

In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods or properties.

What datatype is NaN JavaScript?

In JavaScript, NaN is a number that is not a legal number. The Number. isNaN() method returns true if the value is NaN , and the type is a Number.

Is null a primitive data type JavaScript?

JavaScript has the primitive types: number , string , boolean , null , undefined , symbol and bigint and a complex type: object .


3 Answers

It's a primitive. You can check in a number of ways:

  • typeof NaN gives "number," not "object."

  • Add a property, it disappears. NaN.foo = "hi"; console.log(NaN.foo) // undefined

  • NaN instanceof Number gives false (but we know it's a number, so it must be a primitive).

It wouldn't really make sense for NaN to be an object, because expressions like 0 / 0 need to result in NaN, and math operations always result in primitives. Having NaN as an object would also mean it could not act as a falsey value, which it does in some cases.

like image 113
Dagg Nabbit Avatar answered Oct 20 '22 10:10

Dagg Nabbit


NaN is a primitive Number value. Just like 1, 2, etc.

like image 42
kapa Avatar answered Oct 20 '22 12:10

kapa


NaN is a property of the global object.

The initial value of NaN is Not-A-Number — the same as the value of Number.NaN. In modern browsers, NaN is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it.

It is rather rare to use NaN in a program. It is the returned value when Math functions fail (Math.sqrt(-1)) or when a function trying to parse a number fails (parseInt("blabla")).

Reference

like image 1
Katti Avatar answered Oct 20 '22 11:10

Katti