Why do we need the NaN value when we can throw TypeErrors?

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 and because JavaScript is the language I am primarily familiar with, but I know this applies to other languages as well.

Answers:

Answer

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.

Answer

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.

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.