Alright so I've been learning Javascript for 3 months and have gotten some pretty good exposure to solving several tasks. At the beginning of my book they have examples of NaN but they usually involve things like
NaN === NaN; // false
Number.NaN === NaN; // false
isNaN(NaN); // true
isNaN(Number.NaN); // true
I've even looked on other stackoverflow posts and I still don't see a scenario of where I can use it in. That being said, in what situations does this global property help me? What are some practical situations in an actual program?
NaN is the number which results from math operations which make no sense:
Number('abc'); // NaN
0 / 0; // NaN
Math.sqrt(-1); // NaN
Math.log(-1); // NaN
Math.asin(2); // NaN
When you do some math opertion and some operand is NaN, it will propagate to the result:
NaN + 2; // NaN
NaN * 0; // NaN
1 / NaN; // NaN
Math.pow(NaN, 2); // NaN
NaN is most useful when you have a value that's not a number (but ought to have been). You'll only get NaN back from the standard APIs in a few places, in particular parseInt:
The parseInt function converts its first argument to a string, parses it, and returns an integer or NaN.
Much of the value here is that once NaN has been introduced to a chain of math operators, the operations are defined (even if they wouldn't have made sense with the initial operands, thus producing NaN) and will continue returning NaN. Most of the math operators, as you can see from the / instructions, have a clause to immediately return NaN if either operand is already not a number.
This question already has answers here:
Why does typeof NaN return 'number'?
(21 answers)
Closed 7 years ago.
NaN represents Not-A-Number.
It appears that angular.isNumber thinks it is a number. (angularjs 1.4.2)
Why does angular.isNumber return true for NaN input?
thanks
Quoting IgorMinar, Angular Developer in this exact question:
$ node
> typeof NaN
'number'
It kind of makes sense if you squint with both eyes and plug your
ears.
If you deliberately use NaN in your app, you should use isNaN instead
of angular.isNumber.
I'm inclined to say that the current behavior, even though a bit
surprising, is consistent with how NaN is being treated in javascript.
If you have some good arguments for changing the behavior please share
them with us.
So the question really goes for the javascript standard itself not for Angular
And to answer this question we must go to ECMAScript 5 specification of number type, of course it says:
4.3.20 Number type
set of all possible Number values including the special “Not-a-Number”
(NaN) values, positive infinity, and negative infinity
4.3.23 NaN
number value that is a IEEE 754 “Not-a-Number” value
So yes, according to the latest ECMAScript Specification i'm a number
Here's the best way that I can think of to explain this.
Although the value of NaN represents something that is not a number, the value NaN itself is still a number type (in the type system sense).
It's also a defined value for a floating point number in IEEE 754, which is what JavaScript uses for numbers. It is sensible that values infinity and NaN would be number types.
The ECMA spec defines NaN as a IEEE 754 Not-a-Number number value. One reason for the NaN global being a number are comparison purposes. It is also needed to represent undefined numerical results, like the value of Math.sqrt(-1). So it’s not particularly AngularJS specific. Consider the following:
typeof NaN === "number" // true
typeof NaN === typeof NaN // true
typeof NaN === typeof 123 // true
NaN === NaN // false
isNaN(NaN) // true
isNaN(123) // false
isNaN('123') // false
isNaN('|23') // true
So isNumber returns true for NaN because it is a Number. To check for numerics, use isNaN().
Most likely angular just uses the type of what you pass in. if the type is number then it returns true.
If you want to know if something is a number (excluding NaN) you can do the following.
function isNumber(val){
return angular.isNumber(val) && (val == val);
}
This works by first determing if val is a number. If it is check to see if it's NaN.
NaN is not equal to itself (or any other number for that matter).
it's not related to angular, it's JavaScript
try this
typeof NaN
it will return number
There are really two meanings of "number" here:
the abbreviation "NaN" means that there is no meaningful answer to a particular mathematical operation; you could say "no such number"
however, every value in a language like JS has a type, and the type of data which goes into and out of mathematical operations is known in JS as "number"; thus when JS wants a special value to say that a mathematical operation has no answer, that special value is a special number
Note that this apparent contradiction is less obvious in other languages, because JS is unusual in having only one numeric type, rather than (at least) integer and real/float types. Having NaN as a floating point value is standard across pretty much all modern languages, but because of the word "number", it perhaps seems more surprising in JS.
The Angular function is one of a set of utilities for testing the type of a value. The documentation for it mentions that it returns true for infinities and NaN, and points to the standard isFinite function for when that's not desirable.
This question already has answers here:
What is the rationale for all comparisons returning false for IEEE754 NaN values?
(12 answers)
Closed 10 years ago.
Why are these two different?
var x = NaN; //e.g. Number("e");
alert(isNaN(x)); //true (good)
alert(x == NaN); //false (bad)
Nothing is equal to NaN. Any comparison will always be false.
In both the strict and abstract comparison algorithms, if the types are the same, and either operand is NaN, the result will be false.
If Type(x) is Number, then
If x is NaN, return false.
If y is NaN, return false.
In the abstract algorithm, if the types are different, and a NaN is one of the operands, then the other operand will ultimately be coerced to a number, and will bring us back to the scenario above.
The equality and inequality predicates are non-signaling so x = x returning false can be used to test if x is a quiet NaN.
Source
This is the rule defined in IEEE 754 so full compliance with the specification requires this behavior.
The following operations return NaN
The divisions 0/0, ∞/∞, ∞/−∞, −∞/∞, and −∞/−∞
The multiplications 0×∞ and 0×−∞
The power 1^∞
The additions ∞ + (−∞), (−∞) + ∞ and equivalent subtractions.
Real operations with complex results:
The square root of a negative number
The logarithm of a negative number
The tangent of an odd multiple of 90 degrees (or π/2 radians)
The inverse sine or cosine of a number which is less than −1 or greater than +1.
The following operations return values for numeric operations. Hence typeof Nan is a number. NaN is an undefined number in mathematical terms. ∞ + (-∞) is not equal to ∞ + (-∞). But we get that NaN is typeof number because it results from a numeric operation.
From wiki:
I know the rule:
If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers if possible; else if either operand is a string, the other operand is converted to a string if possible.
So, if("true") passes but if("true" == true) fails because it is handle like if(NaN == 1).
I was wondering what the rational is behind this when one value is boolean. In other weak typed languages like php, this is handle this differently--if one value is a boolean, the other is converted to a boolean for comparisons (and not covert both to numbers as in javascript).
I'm assuming this choice was made for the == operator on careful consideration. Can anyone provide rational as to why this was the chosen functionality? Is there a common use case that this was chosen to address? I'm betting is wasn't just a mistake.
A remarkably quick response just in from Brendan Eich from the es-discuss#mozilla.org mailing list :
Consider Perl:
$ perl -e 'print 0 == "true";'
1
Ok, poor rationale -- but I created JS in May 1995, in the shadow of AWK, Perl 4, Python 1.2 (IIRC), TCL.
I should have paid more attention to AWK than Perl, given
$ awk 'END {print(0 == "0")}'
1D
$ awk 'END {print(0 == "")}'
0D
In some ways, JS's == operator splits the difference between Perl (where non-numeric strings such as "true" convert to 0) and AWK (where only "0" converts to 0) by converting to NaN. That way, at least, we have
js> 0 == ""
true
js> 0 == "true"
false
But the full truth is not that I was carefully emulating other languages. Rather, some Netscapers working to embed JS (then "Mocha") in a PHP-like server (LiveWire) wanted sloppy conversions, so programmers could match HTTP header strings (server side) or HTML form fields (client side) against, e.g., 404 and the like, without explicit coercion by the programmer.
But it was the 90s, I was in a tearing hurry, these ex-Borland Netscapers were persistent. So, as I said at Strange Loop last year, "I was an idiot! I gave them what they wanted!"
Implicit conversions are my biggest regret in JS's rushed design, bar none. Even including 'with'!
Does anyone know the exact reason the choice was made not to convert to boolean any value compared against a boolean in with the == operator?
The general idea is the narrower type should widen. Thus, true == 1 follows by projecting boolean {false, true} onto {0, 1}, as in C++.
But why not widen true to string, since the other operand in your example is "true"? Good question. The bias toward comparing strings as numbers if either operand is a number or a boolean stems from the HTTP header and numeric-string HTML form field use-cases. Not good reasons, again, but that's how JS "works" :-|.
You can see this in the ECMA-262 Edition 5.1 spec, 11.9.3 The Abstract Equality Comparison Algorithm, steps 6 & 7 (read in light of steps 4 & 5):
4. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
5. If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
6. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
7. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
This is all in a big "else clause where Type(x) and Type(y) for x == y are not the same.
Sorry there's no pearl (sic) of wisdom here. In addition to implicit conversions, == and != do not widen operands directly (no intermediate conversions) to the narrowest width that can hold the other operand without data loss. This narrowing string to number is just a botch.
If we fixed this botch, we'd still have:
0 == "0"
1 == "1"
true != "1"
false != "0"
But we would also have what your example wants:
true == "true"
false != ""
Per my calling the preference for number over string conversion a botch, we would not have true == "1" or false == "0", because that narrows from string to number. It's true the narrowing loses no bits, and one can widen 0 back to "0" and 1 back to "1", but I meant to illustrate what removing all number-over-string bias from the implicit conversion spec for == would do.
Would such a change break a lot of code on the web? I'd bet large sums it would.
Some take this botch, on top of any implicit conversion under the hood, as another reason to use === and !== always (because they never convert), and to utterly shun == and !=. Others disagree (especially when testing x == null, a one-operator way to test x === null || x === undefined).
Since the web grows mostly-compatibly until very old forms die off, we're stuck with == and !=, so I say it pays to learn what the sloppy equality operators do. Having done that, it seems to me one may use them where they win: when you know the operands are same-type, e.g.
typeof x == "function", etc.
x == null
And otherwise, use === and !==.
The bias toward comparing strings as numbers if either operand is a number or a boolean stems from the HTTP header and numeric-string HTML form field use-cases. Not good reasons, again, but that's how JS "works" :-|.
One more note: it could be argued that narrowing from string to number would be ok (as in, useful most of the time, and not unsafe) if any non-numeric, non-empty string-to-number implicit conversion attempt threw an exception.
Here's where another path-dependent bias in JS's design bit: no try/catch in JS1 or any ECMA-262 standard till ES3.
The lack of exception handling also meant undefined is imputed for missing obj.foo property get where obj has no such property. That is still biting back, perhaps as much as or more than implicit conversions bite ==. It is also the basis of web JS's winning "object detection" pattern, which fairly beats all other versioning schemes I've seen, especially a-priori ones based on explicit numbering and opt-in.
If only I'd taken the time to add an existential operator for object detection, so one could write
function emulateRequestAnimationFrame(...) {...}
if (!window.requestAnimationFrame?)
window.requestAnimationFrame = emulateRequestAnimationFrame;
IOW, if only I'd made window.noSuchProperty throw but window.noSuchProperty? evaluate to truthy or false (details still TBD, see the "fail-fast object destructuring" thread revival, the Nil idea).
I think some clarification is in order. According to the ECMA specification the entire expression for the if statement (the part within the parentheses) is converted to a boolean.
So imagine it like this:
if (ToBoolean("true" == true)) { //false
vs
if (ToBoolean("true")) { //true
I suppose the rational for why the ToBoolean coercion was added to the if expression was to ensure the expression always evaluates safely and correctly.
ToBoolean coerces a single value to a boolean. A comparison does not coerce each value to a boolean, that wouldn't make sense as you get some pretty strange results. It checks for equality, a different operation. As for why one value isn't converted to boolean when the other is one I am not sure, but try the Mozilla ECMA mailing list: https://mail.mozilla.org/listinfo/es-discuss
See:
http://www.ecma-international.org/ecma-262/5.1/#sec-9.2
http://www.ecma-international.org/ecma-262/5.1/#sec-12.5
http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.1
http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3
http://www.ecma-international.org/ecma-262/5.1/#sec-8.7.1
Just out of curiosity.
It doesn't seem very logical that typeof NaN is number. Just like NaN === NaN or NaN == NaN returning false, by the way. Is this one of the peculiarities of JavaScript, or would there be a reason for this?
Edit: thanks for your answers. It's not an easy thing to get ones head around though. Reading answers and the wiki I understood more, but still, a sentence like
A comparison with a NaN always returns an unordered result even when comparing with itself. The comparison predicates are either signaling or non-signaling, the signaling versions signal an invalid exception for such comparisons. The equality and inequality predicates are non-signaling so x = x returning false can be used to test if x is a quiet NaN.
just keeps my head spinning. If someone can translate this in human (as opposed to, say, mathematician) readable language, I would be grateful.
Well, it may seem a little strange that something called "not a number" is considered a number, but NaN is still a numeric type, despite that fact :-)
NaN just means the specific value cannot be represented within the limitations of the numeric type (although that could be said for all numbers that have to be rounded to fit, but NaN is a special case).
A specific NaN is not considered equal to another NaN because they may be different values. However, NaN is still a number type, just like 2718 or 31415.
As to your updated question to explain in layman's terms:
A comparison with a NaN always returns an unordered result even when comparing with itself. The comparison predicates are either signalling or non-signalling, the signalling versions signal an invalid exception for such comparisons. The equality and inequality predicates are non-signalling so x = x returning false can be used to test if x is a quiet NaN.
All this means is (broken down into parts):
A comparison with a NaN always returns an unordered result even when comparing with itself.
Basically, a NaN is not equal to any other number, including another NaN, and even including itself.
The comparison predicates are either signalling or non-signalling, the signalling versions signal an invalid exception for such comparisons.
Attempting to do comparison (less than, greater than, and so on) operations between a NaN and another number can either result in an exception being thrown (signalling) or just getting false as the result (non-signalling or quiet).
The equality and inequality predicates are non-signalling so x = x returning false can be used to test if x is a quiet NaN.
Tests for equality (equal to, not equal to) are never signalling so using them will not cause an exception. If you have a regular number x, then x == x will always be true. If x is a NaN, then x == x will always be false. It's giving you a way to detect NaN easily (quietly).
It means Not a Number. It is not a peculiarity of javascript but common computer science principle.
From http://en.wikipedia.org/wiki/NaN:
There are three kinds of operation
which return NaN:
Operations with a NaN as at least one operand
Indeterminate forms
The divisions 0/0, ∞/∞, ∞/−∞, −∞/∞, and −∞/−∞
The multiplications 0×∞ and 0×−∞
The power 1^∞
The additions ∞ + (−∞), (−∞) + ∞ and equivalent subtractions.
Real operations with complex results:
The square root of a negative number
The logarithm of a negative number
The tangent of an odd multiple of 90 degrees (or π/2 radians)
The inverse sine or cosine of a number which is less than −1 or
greater than +1.
All these values may not be the same. A simple test for a NaN is to test value == value is false.
The ECMAScript (JavaScript) standard specifies that Numbers are IEEE 754 floats, which include NaN as a possible value.
ECMA 262 5e Section 4.3.19: Number value
primitive value corresponding to a double-precision 64-bit binary format IEEE 754 value.
ECMA 262 5e Section 4.3.23: NaN
Number value that is a IEEE 754 "Not-a-Number" value.
IEEE 754 on Wikipedia
The IEEE Standard for Floating-Point Arithmetic is a technical standard established by the Institute of Electrical and Electronics Engineers and the most widely used standard for floating-point computation [...]
The standard defines
arithmetic formats: sets of binary and decimal floating-point data, which consist of finite numbers (including signed zeros and subnormal numbers), infinities, and special "not a number" values (NaNs)
[...]
typeof NaN returns 'number' because:
ECMAScript spec says the Number type includes NaN:
4.3.20 Number type
set of all possible Number values including the special “Not-a-Number”
(NaN) values, positive infinity, and negative infinity
So typeof returns accordingly:
11.4.3 The typeof Operator
The production UnaryExpression : typeof UnaryExpression is
evaluated as follows:
Let val be the result of evaluating UnaryExpression.
If Type(val) is Reference, then
If IsUnresolvableReference(val) is true, return "undefined".
Let val be GetValue(val).
Return a String determined by Type(val) according to Table 20.
Table 20 — typeof Operator Results
==================================================================
| Type of val | Result |
==================================================================
| Undefined | "undefined" |
|----------------------------------------------------------------|
| Null | "object" |
|----------------------------------------------------------------|
| Boolean | "boolean" |
|----------------------------------------------------------------|
| Number | "number" |
|----------------------------------------------------------------|
| String | "string" |
|----------------------------------------------------------------|
| Object (native and does | "object" |
| not implement [[Call]]) | |
|----------------------------------------------------------------|
| Object (native or host and | "function" |
| does implement [[Call]]) | |
|----------------------------------------------------------------|
| Object (host and does not | Implementation-defined except may |
| implement [[Call]]) | not be "undefined", "boolean", |
| | "number", or "string". |
------------------------------------------------------------------
This behavior is in accordance with IEEE Standard for Floating-Point Arithmetic (IEEE 754):
4.3.19 Number value
primitive value corresponding to a double-precision 64-bit binary
format IEEE 754 value
4.3.23 NaN
number value that is a IEEE 754 “Not-a-Number” value
8.5 The Number Type
The Number type has exactly 18437736874454810627 (that is, 253−264+3)
values, representing the double-precision 64-bit format IEEE 754
values as specified in the IEEE Standard for Binary Floating-Point
Arithmetic, except that the 9007199254740990 (that is, 253−2) distinct
“Not-a-Number” values of the IEEE Standard are represented in
ECMAScript as a single special NaN value. (Note that the NaN value
is produced by the program expression NaN.)
NaN != NaN because they are not necessary the SAME non-number. Thus it makes a lot of sense...
Also why floats have both +0.00 and -0.00 that are not the same. Rounding may do that they are actually not zero.
As for typeof, that depends on the language. And most languages will say that NaN is a float, double or number depending on how they classify it... I know of no languages that will say this is an unknown type or null.
NaN is a valid floating point value (http://en.wikipedia.org/wiki/NaN)
and NaN === NaN is false because they're not necessarily the same non-number
NaN stands for Not a Number. It is a value of numeric data types (usually floating point types, but not always) that represents the result of an invalid operation such as dividing by zero.
Although its names says that it's not a number, the data type used to hold it is a numeric type. So in JavaScript, asking for the datatype of NaN will return number (as alert(typeof(NaN)) clearly demonstrates).
A better name for NaN, describing its meaning more precisely and less confusingly, would be a numerical exception. It is really another kind of exception object disguised as having primitive type (by the language design), where at the same it is not treated as primitive in its false self-comparison. Whence the confusion. And as long as the language "will not make its mind" to choose between proper exception object and primitive numeral, the confusion will stay.
The infamous non-equality of NaN to itself, both == and === is a manifestation of the confusing design forcing this exception object into being a primitive type. This breaks the fundamental principle that a primitive is uniquely determined by its value. If NaN is preferred to be seen as exception (of which there can be different kinds), then it should not be "sold" as primitive. And if it is wanted to be primitive, that principle must hold. As long as it is broken, as we have in JavaScript, and we can't really decide between the two, the confusion leading to unnecessary cognitive load for everyone involved will remain. Which, however, is really easy to fix by simply making the choice between the two:
either make NaN a special exception object containing the useful information about how the exception arose, as opposed to throwing that information away as what is currently implemented, leading to harder-to-debug code;
or make NaN an entity of the primitive type number (that could be less confusingly called "numeric"), in which case it should be equal to itself and cannot contain any other information; the latter is clearly an inferior choice.
The only conceivable advantage of forcing NaN into number type is being able to throw it back into any numerical expression. Which, however, makes it brittle choice, because the result of any numerical expression containing NaN will either be NaN, or leading to unpredictable results such as NaN < 0 evaluating to false, i.e. returning boolean instead of keeping the exception.
And even if "things are the way they are", nothing prevents us from making that clear distinction for ourselves, to help make our code more predictable and easierly debuggable. In practice, that means identifying those exceptions and dealing with them as exceptions. Which, unfortunately, means more code but hopefully will be mitigated by tools such as TypeScript of Flowtype.
And then we have the messy quiet vs noisy aka signalling NaN distinction. Which really is about how exceptions are handled, not the exceptions themselves, and nothing different from other exceptions.
Similarly, Infinity and +Infinity are elements of numeric type arising in the extension of the real line but they are not real numbers. Mathematically, they can be represented by sequences of real numbers converging to either + or -Infinity.
Javascript uses NaN to represent anything it encounters that can't be represented any other way by its specifications. It does not mean it is not a number. It's just the easiest way to describe the encounter. NaN means that it or an object that refers to it could not be represented in any other way by javascript. For all practical purposes, it is 'unknown'. Being 'unknown' it cannot tell you what it is nor even if it is itself. It is not even the object it is assigned to. It can only tell you what it is not, and not-ness or nothingness can only be described mathematically in a programming language. Since mathematics is about numbers, javascript represents nothingness as NaN. That doesn't mean it's not a number. It means we can't read it any other way that makes sense. That's why it can't even equal itself. Because it doesn't.
This is simply because NaN is a property of the Number object in JS, It has nothing to do with it being a number.
The best way to think of NAN is that its not a known number. Thats why NAN != NAN because each NAN value represents some unique unknown number. NANs are necessary because floating point numbers have a limited range of values. In some cases rounding occurs where the lower bits are lost which leads to what appears to be nonsense like 1.0/11*11 != 1.0. Really large values which are greater are NANs with infinity being a perfect example.
Given we only have ten fingers any attempt to show values greater than 10 are impossible, which means such values must be NANs because we have lost the true value of this greater than 10 value. The same is true of floating point values, where the value exceeds the limits of what can be held in a float.
NaN is still a numeric type, but it represents value that could not represent a valid number.
Because NaN is a numeric data type.
NaN is a number from a type point of view, but is not a normal number like 1, 2 or 329131. The name "Not A Number" refers to the fact that the value represented is special and is about the IEEE format spec domain, not javascript language domain.
If using jQuery, I prefer isNumeric over checking the type:
console.log($.isNumeric(NaN)); // returns false
console.log($.type(NaN)); // returns number
http://api.jquery.com/jQuery.isNumeric/
Javascript has only one numeric data type, which is the standard 64-bit double-precision float. Everything is a double. NaN is a special value of double, but it's a double nonetheless.
All that parseInt does is to "cast" your string into a numeric data type, so the result is always "number"; only if the original string wasn't parseable, its value will be NaN.
We could argue that NaN is a special case object. In this case, NaN's object represents a number that makes no mathematical sense. There are some other special case objects in math like INFINITE and so on.
You can still do some calculations with it, but that will yield strange behaviours.
More info here: http://www.concentric.net/~ttwang/tech/javafloat.htm (java based, not javascript)
You've got to love Javascript. It has some interesting little quirks.
http://wtfjs.com/page/13
Most of those quirks can be explained if you stop to work them out logically, or if you know a bit about number theory, but nevertheless they can still catch you out if you don't know about them.
By the way, I recommend reading the rest of http://wtfjs.com/ -- there's a lot more interesting quirks than this one to be found!
The value NaN is really the Number.NaN hence when you ask if it is a number it will say yes. You did the correct thing by using the isNaN() call.
For information, NaN can also be returned by operations on Numbers that are not defined like divisions by zero or square root of a negative number.
It is special value of Number type as POSITIVE_INFINITY
Why? By design
An example
Imagine We are converting a string to a number:
Number("string"); // returns NaN
We changed the data type to number but its value is not a number!