Why do programming languages have a
Math.floor('string'); //--> NaN
Why not just throw a TypeError?
TypeError: Expected number instead of string
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
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.
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
NaNs (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
©2020 All rights reserved.