Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the reserved keyword for NaN in javascript?

Tags:

javascript

nan

if i want to test the result of an expression and the function would return NaN how would i check that?
examples:
$('amount').value.toInt()!='NaN'
^ does not work and i assume that the returned value is not a string,
$('amount').value.toInt()!=NaN
^ doesnt seem to work either and this one seems obvious

so how do i check wether the returned value is not a number?

like image 930
lock Avatar asked Feb 18 '09 04:02

lock


People also ask

What is the NaN in JavaScript?

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. NaN . In modern browsers, NaN is a non-configurable, non-writable property.

How does JavaScript handle NaN?

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.

Is NaN a keyword?

Regarding your second point: They are not needed, that's why undefined and NaN are not keywords. @Baszz - by that logic it should be possible to overwrite the value of true , false , null , etc., but it isn't.


2 Answers

The NaN value is defined to be unequal to everything, including itself. Test if a value is NaN with the isNaN() function, appropriately enough. (ECMAScript 6 adds a Number.isNan() function with different semantics for non-number arguments, but it's not supported in all browsers yet as of 2015).

There are two built-in properties available with a NaN value: the global NaN property (i.e. window.NaN in browsers), and Number.NaN. It is not a language keyword. In older browsers, the NaN property could be overwritten, with potentially confusing results, but with the ECMAScript 5 standard it was made non-writable.

  • As @some pointed out in the comments, there is also the global function isFinite() which may be useful.
like image 102
Miles Avatar answered Sep 19 '22 05:09

Miles


the best way to check the result of numeric operation against NaN is to aproach this way , example:

var x  = 0;
var y  = 0;
var result = x/y;  // we know that result will be NaN value
// to test if result holds a NaN value we should use the following code :

if(result !=result){
console.log('this is an NaN value');
} 

and it's done.

the trick is that NaN can't be compared to any other value even with it self(NaN !=NaN is always true so we can take advantage of this and compare result against itself)

this is JavaScript(a good and bizarre language)

like image 26
ismnoiet Avatar answered Sep 21 '22 05:09

ismnoiet