What exactly does isNaN() do in javaScript? [duplicate] - javascript

This question already has answers here:
Is Number.IsNaN() more broken than isNaN()
(11 answers)
Closed 7 years ago.
isNaN() returns false if and only if the argument is number.
var a = new Number(1);
By doing so, a is an object now.
So why is isNaN(a) returning false?

isNaN() tests whether an input is NOT a number.
var a = new Number(1)
a is a number object. Therefore isNaN() returns false.
Here is a nice documentation containing isNaN() behaviors with different edge cases. Unfortunately some of them are not as intuitive as hoped, so it's worth reading.

The global isNaN() function coerces its argument to a number value before testing for NaN. Your object converts cleanly to the number 1, and 1 is not NaN.
Note that isNaN("1") also returns false, because the string "1" converts cleanly to a number that isn't NaN.
The isNaN function is not really intended as a general-purpose test for whether something is or is not a number. It's a test for the specific numeric value NaN. It's often used as a general-purpose test, and that (mostly) works because JavaScript returns NaN when an attempt to convert a value to a number fails. That's somewhat impure, because NaN exists as a marker with a specific purpose in the floating point system.
Some JavaScript environments have Number.isNaN() in addition to the global isNaN. The function on the Number constructor does not perform a type coercion first. For that reason, Number.isNaN("foo") returns false, because even though the string "foo" cannot be converted to a number cleanly, it's not the constant NaN.

Related

Is there any reason not to use the plus operator instead of Number() or parseInt() to return a number? [duplicate]

This question already has answers here:
parseInt vs unary plus, when to use which?
(6 answers)
What is the difference between parseInt() and Number()?
(11 answers)
Closed 4 years ago.
Basically, I'm trying to figure out what the difference is between these 3 statements? Is there any reason to use one instead of the others? Is the first one bad practice (it works but I never see it and doesn't seem to be taught anywhere)?
+'21';
Number('21');
parseInt('21');
parseInt parses the string up to the first non-digit number and returns what it found,
For example: parseInt('123abc') // returns 123;
Number tries to convert the entire string into a number if it can.
ForExample: Number('123abc') // returns NaN
Unary plus operator can also be used to convert a string into a number, but it is not very readable when it is being used with other expressions and operators
Internally, +'21' will work in the same way as Number('21') * 1
As far as I know the first two are completely equivalent, and the choice between them is a matter of taste. (Personally I prefer the unary + because it's more concise, and well understood by most JS developers.)
parseInt is different because it reads a number value from the start of the string and ignores the rest when it reaches a non-numeric character. A common use is getting the underlying number from a CSS value like "20px". Note that the other two methods would fail with a NaN in this case.

EloquentJavaScript: !Number.isNaN() what is the purpose? [duplicate]

Soooooo isNaN is apparently broken in JavaScript, with things like:
isNaN('')
isNaN(' ')
isNaN(true)
isNaN(false)
isNaN([0])
Returning false, when they appear to all be... Not a Number...
In ECMAScript 6, the draft includes a new Number.isNaN but it looks like (imo) that this is also broken...
I would expect
Number.isNaN('RAWRRR')
To return true, since it's a string, and cannot be converted to a number... However...
It seems that things that I would consider... not a number, are indeed, not, not a number...
http://people.mozilla.org/~jorendorff/es6-draft.html#sec-isfinite-number
The examples on MDN say:
Number.isNaN("blabla"); // e.g. this would have been true with isNaN
I don't understand how this is "More robust version of the original global isNaN." when I cannot check to see if things are not a number.
This would mean we're still subjected to doing actual type checking as well as checking isNaN... which seems silly...
http://people.mozilla.org/~jorendorff/es6-draft.html#sec-isnan-number
The ES3 draft here basically says, everything is always false, except with its Number.NaN
Does anyone else find this is broken or am I just not understanding the point of isNaN?
isNaN() and Number.isNaN() both test if a value is (or, in the case of isNaN(), can be converted to a number-type value that represents) the NaN value. In other words, "NaN" does not simply mean "this value is not a number", it specifically means "this value is a numeric Not-a-Number value according to IEEE-754".
The reason all your tests above return false is because all of the given values can be converted to a numeric value that is not NaN:
Number('') // 0
Number(' ') // 0
Number(true) // 1
Number(false) // 0
Number([0]) // 0
The reason isNaN() is "broken" is because, ostensibly, type conversions aren't supposed to happen when testing values. That is the issue Number.isNaN() is designed to address. In particular, Number.isNaN() will only attempt to compare a value to NaN if the value is a number-type value. Any other type will return false, even if they are literally "not a number", because the type of the value NaN is number. See the respective MDN docs for isNaN() and Number.isNaN().
If you simply want to determine whether or not a value is of the number type, even if that value is NaN, use typeof instead:
typeof 'RAWRRR' === 'number' // false
No, the original isNaN is broken. You are not understanding the point of isNaN.
The purpose of both of these functions is to determine whether or not something has the value NaN. This is provided because something === NaN will always be false and therefore can't be used to test this.
(side note: something !== something is actually a reliable, although counter-intuitive, test for NaN)
The reason isNaN is broken is that it can return true in cases when a value is not actually NaN. This is because it first coerces the value to a number.
So
isNaN("hello")
is true, even though "hello" is not NaN.
If you want to check whether a value actually is a finite number, you can use:
Number.isFinite(value)
If you want to test whether a value is a finite number or a string representation of one, you can use:
Number.isFinite(value) || (Number.isFinite(Number(value)) && typeof value === 'string')
As mentioned in a comment isNaN() and Number.isNaN() both check that the value you pass in is not equal to the value NaN. The key here is that NaN is an actual value and not an evaluated result e.g. "blabla" is a String and the value is "blabla" which means it is not the value "NaN".
A plausible solution would be doing something like:
Number.isNaN(Number("blabla")); //returns true.
The key difference between the two is that the global isNaN(x) function performs a conversion of the parameter x to a number. So
isNaN("blabla") === true
because Number("blabla") results in NaN
There are two definitions of "not a number" here and that's perhaps where the confusion lies. Number.isNaN(x) only returns true for the IEEE 754 floating point specification's definition of Not a Number, for example:
Number.isNaN(Math.sqrt(-1))
as opposed to determining whether the object being passed in is of numeric type or not. Some ways of doing that are:
typeof x === "number"
x === +x
Object.prototype.toString.call(x) === "[object Number]"
Basically, window.isNaN performs a type conversion to a number, then checks if it is NaN. Whereas, Number.isNaN doesn't try to convert its argument to a number. So basically, you can think of window.isNaN, and Number.isNaN as working like so.
window.isNaN = function(n){
return Number(n) !== Number(n);
}
window.Number.isNaN = function(n){
return n !== n;
}
Please note that you don't need actually to use the window. to call isNaN or Number.isNaN. Rather, I am just using it to provide a better distinction between the two similarly-named methods to try to cut down on confusion.
~ Happy Coding!
The following works because NaN is the only value in javascript which is not equal to itself.
Number.isNaN = Number.isNaN || function(value) {
return value !== value;
}
Per, MDN, it (NaN) is the returned value when Math functions fail and as such it is a specific value. Perhaps a better name would have been, MathFunctionFailed.
To determine if something is a number requires parsing which fails nicely over a broad range of non numeric inputs, successfully detecting numbers and strings representing numbers, hence:
function isNumber(v) {return Number.isNaN(parseFloat(v)); }
1. Number.isNaN
alert(Number.isNaN('Hello')); // false
Shouldn't it return true because Hello is a string and its Not A Number right ? But Lets know why it returns false.
MDN docs says :
true if the given value is NaN and its type is Number; otherwise,
false.
Yes Hello value is NaN but the type is string , you can check the type as follows:
alert(typeof `Hello`); // string
Usage:
Use when you want to check the value is both NaN and type is number.
2. isNaN
alert(isNaN('Hello')); // true
MDN docs says:
true if the given value is NaN; otherwise, false.
Usage:
Use when you want to check value is just NaN.
3. jQuery.isNumeric()
Jquery Docs Says :
Determines whether its argument represents a JavaScript number.
alert($.isNumeric('Hello')); // false
alert($.isNumeric(3)); //true
Usage:
Use when you want to check value is a number or can be converted to a number.
Reference
I use a simple workaround to check Number.isNaN():
let value = 'test';
Number.isNaN(-value); // true
value = 42;
Number.isNaN(-value); // false
js trying to convert the value to the negative Number, if the conversion is failed - we have NaN.
Simple, isn't it?
Moreover, online benchmark tests say Number.isNaN is lighter than isNaN.
Number.isNaN(x) checks if x is directly evaluated to NaN or not.
RAWR is not the same as NaN. Think of NaN as an entity to represent the result of some mathematical calculation where the computer does not know how to represent the number.
A mathematical operation is not going to yield a non-numeric result, hence the typeof NaN is number.
The string RAWR had undergone no mathematical operation to yield NaN. However, if you were to call Number.isNaN(+'RAWR'), it would result in NaN since the unary + operator is trying to convert 'RAWR' to a number.
On the other hand, isNaN(y) tells whether y can be converted to a number or not. If isNaN(y) is false, y can be converted to a number. But if isNaN(y) is true, y can not be converted to a number.
So a good rule of thumb is:
Do I want to check if x can be successfully converted to a number? Use isNaN(x) == false in that case. Unsuccessful conversion results in NaN.
Do I want to check if x is evaluated to NaN? Use Number.isNaN(x) == true for that.
#phill, as stated in other responses, neither is broken.
Number.isNaN work on a number or instance of Number, so even Number.isNaN(new Date(NaN)) is false.
isNaN, on the other hand, is generic and tries to convert its parameter to a number before checking it.
If you want to determine if a value is (or contains) NaN, you can use this function:
function valueIsNaN(value) {
// eslint-disable-next-line no-self-compare
return value !== value || typeof value == 'object' && Number.isNaN(value.valueOf());
}

Comparing NaN in javascript [duplicate]

This question already has answers here:
How do I test for NaN? [duplicate]
(2 answers)
Closed 7 years ago.
In Javascript, if we multiply a string with number we get NaN:
console.log("manas" * 5); // result is NaN
Why then does the following code result in false instead of true?
console.log("manas" * 5 == NaN) // results false
Use the isNaN function instead.
console.log(isNaN("manas" * 5));
http://www.w3schools.com/jsref/jsref_isnan.asp
NaN, not a number, is a special type value used to denote an unrepresentable value. With JavaScript, NaN can cause some confusion, starting from its typeof and all to the way the comparison is handled.
Several operations can lead to NaN as the result.
Because there are many ways to represent a NaN, it makes sense that one NaN will not be equal to another NaN.
NaN is a special numeric value which is not equal to anything including itself. To properly test for NaN you need to use isNaN function.
From specification:
Returns true if the argument coerces to NaN, and otherwise returns false.
Here is also useful note from the same ECMAScript section:
A reliable way for ECMAScript code to test if a value X is a NaN is an expression of the form X !== X. The result will be true if and only if X is a NaN.
NaN compares unequal (via ==, !=, ===, and !==) to any other value -- including to another NaN value. Use Number.isNaN() or isNaN() to most clearly determine whether a value is NaN. Or perform a self-comparison: NaN, and only NaN, will compare unequal to itself.
Testing against NaN
In Javascript,
NaN == NaN //always results false.
(self comparison of NaN to itself is always false in javascript)
refer:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN
also see Is NaN equal to NaN?
Javascript is not that smart - when either side of the == operator is Nan, the whole thing evaluates as false (similar to how if leftside of || is false, it doesn't bother looking at right side)
So, even Nan == Nan will return false.
Here's a good article on Nan behaviour
http://ariya.ofilabs.com/2014/05/the-curious-case-of-javascript-nan.html

Why NaN is greater than any number in JavaScript? [duplicate]

This question already has answers here:
What is the rationale for all comparisons returning false for IEEE754 NaN values?
(12 answers)
Closed 8 years ago.
Here is an example:
parseInt(50) > parseInt('a');
When executing this on a console, it will return false. My original code looks somewhat like this:
variableB = parseInt(jQuery('some-element').html());
if(parseInt(variableA) > variableB)
// do something
else
// do something else
Sometimes the some-element will not be filled and thus return NaN. When this happens, I do want the else block to be executed. I am actually getting what I expect, but I just want to make sure that it indeed is intended to work this way.
In IEEE 754 arithmethic, the floating-point model used by JavaScript, NaN (or not-a-number) is, by definition, not less than, equal to, or greater than any other number.
Notice that this even applies to two NaNs: if x = NaN and y = NaN, the comparison x === y will return false.
Below I quote the portion of the IEEE 754 Standard (Section 5.11) where this behavior is specified:
Four mutually exclusive relations are possible: less than, equal,
greater than, and unordered. The last case arises when at least one
operand is NaN. Every NaN shall compare unordered with
everything, including itself.
All comparisons involving NaN will always return false.
NaN is neither less than nor greater than any number.

Why parseInt() doesn't convert "true" to number, while multiplying does? [duplicate]

This question already has answers here:
parseInt vs unary plus, when to use which?
(6 answers)
Closed 8 years ago.
I started from expression returning true (I choose 1==1) and wrote it in console
cosole.log(1==1);
It logs true. Now I want to convert it to integer (1) and wrap it in parseInt()
console.log(parseInt(1==1));
It logs NaN. Looks like it is trying to convert 1==1 to string before it converts it to number.
Then I'll simply multiply 1==1 by 1.
console.log((1==1)*1);
It logs 1.
Why in first case it converts it converts true to string before converting it to integer (resulting NaN) while I want to convert it to string and in the second case it converts true directly to integer? I'd expect that true*1 will be NaN too.
parseInt, by virtue of being a “parse”r, should take a string and produce an integer, so it converts its argument to a string. *, because it’s multiplication, converts its arguments to numbers.
If you want to convert anything to an (32-bit) integer, | 0 works; it’s a 32-bit bitwise integer operation, and can’t result in NaN, because that’s not a 32-bit integer.
Just to emphasize that parseInt is a wholly inappropriate way of casting anything but a string to an integer: what does this give you?
parseInt(5000000000000000000000000)
(For numbers that big, use Math.round(x), or Math.round(+x) if you like to be explicit.)
parseInt(bool) == NaN
parseInt(bool*1) == parseInt(int) == int
I believe Javascript makes true = 1 and false = 0 when you multiply it.
EDIT: to further this, parseInt(bool*bool) would also work

Categories

Resources