Primitive Data Types, Arrays, Loops, and Conditions / Part 2 - Page 2 | WebReference

Primitive Data Types, Arrays, Loops, and Conditions / Part 2 - Page 2


[previous] [next]

Primitive Data Types, Arrays, Loops, and Conditions - Part 2 [con't]

Exponent Literals

1e1 (can also be written as 1e+1 or 1E1 or 1E+1) represents the number one with one zero after it, or in other words 10. Similarly, 2e+3 means the number 2 with 3 zeros after it, or 2000.

2e+3 means moving the decimal point 3 digits to the right of the number 2. There's also 2e-3 meaning you move the decimal point 3 digits to the left of the number 2. [See the example here.]

Infinity

There is a special value in JavaScript called Infinity. It represents a number too big for JavaScript to handle. Infinity is indeed a number, as typing typeof Infinity in the console will confirm. You can also quickly check that a number with 308 zeros is ok, but 309 zeros is too much. To be precise, the biggest number JavaScript can handle is 1.7976931348623157e+308 while the smallest is 5e-324.

Dividing by 0 will give you infinity.

Infinity is the biggest number (or rather a little bigger than the biggest), but how about the smallest? It's infinity with a minus sign in front of it, minus infinity.

Does this mean you can have something that's exactly twice as big as Infinity— from 0 up to infinity and then from 0 down to minus infinity? Well, this is purely for amusement and there's no practical value to it. When you sum infinity and minus infinity, you don't get 0, but something that is called NaN (Not A Number).

Any other arithmetic operation with Infinity as one of the operands will give you Infinity:

NaN

What was this NaN you saw in the example above? It turns out that despite its name, "Not A Number", NaN is a special value that is also a number.

You get NaN when you try to perform an operation that assumes numbers but the operation fails. For example, if you try to multiply 10 by the character "f", the result is NaN, because "f" is obviously not a valid operand for a multiplication.

NaN is contagious, so if you have even only one NaN in your arithmetic operation, the whole result goes down the drain.


[previous] [next]