Why do programming languages have a NaN
value?
Math.floor('string'); //--> NaN
Why not just throw a TypeError?
TypeError: Expected number instead of string
The question is tagged both javascript and language-agnostic because JavaScript is the language I am primarily familiar with, but I know this applies to other languages as well.
In typed languages, you must put a number in a number variable, even when you don't have a number. You put NaN (that's why typeof NaN
is "number"
in JavaScript). That's just like null
for object references when you don't have better.
And exceptions, which break the flow of instructions, really aren't so popular for everybody. Some might argue that they should be used for exceptionnal cases, not the simple fact that a string isn't parsable as a number.
Note that NaN
can also be the result of a mathematical operation, occuring when it's not possible to decide what should be the result (for example 0 * Infinity
). It's simpler to handle this with NaN than to include branching in all operations.
To be uncreative, it's because NaN
s (as well as other non-numeric quantities, like infinity) are part of the IEEE 754 floating-point standard, which many programming languages implement.
It's designed to allow for "special cases" in numeric computation to be evaluated like normal numbers without interrupting the calculations. That means no exceptions. In lieu of that, NaNs are generally propagated through operations until they come out on the other side, for better or worse.
JavasScript is a weakly typed language. Error throwing is expensive. Look through jquery or underscore and you will see that errors are rarely thrown, only for "exceptional" cases. It is less costly and easier to deal with values such as NaN
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With