Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 639
Web_Designer Avatar asked Jul 23 '13 17:07

Web_Designer


3 Answers

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.

like image 125
Denys Séguret Avatar answered Oct 29 '22 13:10

Denys Séguret


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.

like image 23
voithos Avatar answered Oct 29 '22 13:10

voithos


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.

like image 20
mark_huffington Avatar answered Oct 29 '22 13:10

mark_huffington