Virtually all programming languages use a variety of data types to represent numbers; for instance bytes, ints, floats and doubles. Back when memory and processing power was expensive, we needed to be careful to limit our usages. It is quicker to operate on smaller number types, such as bytes and chars, than on floats and doubles. Likewise, the larger number types take up more memory. The limitiation of using different number types is that we need to be careful to use suitable number types to avoid overflow errors.

Javascript was always designed to be an easy language to use. For that reason, it has only one number type: Number. Number is a 64-bit floating point (or as we usually call it, a double), which allows developers to forget about overflow issues. Additionally, now memory is cheap and we have an abundance of processing power, we don’t have to worry so much about the effects of using larger data types. Perhaps in 1995 when javascript was first introduced this was not so true as it is today, but with hindsight it was clearly a good decision.

Number, like everything else in javascript, extends Object, which means that it can have functions. There are five functions that are included natively: toExponential(), toFixed(), toPrecision(), toString() and valueOf(); but since Number is an object, we are also able to extend it by adding new functions to its prototype. [Although on the whole this practise is not advised unless you are building a general use utility framework such as underscore.js]

There is one gotcha with the javascript, and that is NaN. NaN, or Number.NaN, is the result of an illegal math operation, such as division by zero or the square root of a negative number. Oddly enough however, **NaN !== NaN**. This means that the following statements are all true:

3/0 !== 3/0 Math.Sqrt(-4) !== Math.Sqrt(-4) Math.abs("text") !== Math.abs("text")

This seems a little odd until you consider that each of the expressions returns the same result, so the inequality makes more sense when if we muddle up the examples:

3/0 !== Math.abs("text") Math.Sqrt(-4) !== Math.abs("text") Math.Sqrt(-4) !== 3/0

Since javascript doesn’t know what either side of the condition really is – as it evaluates all as NaN – it cannot accurately conclude whether or not they are really equal. People are critical of this, but to me it really seems to be the only thing that makes sense.

Pingback:Javascript Primitives » Jordan Wallwork