Extra large or extra small numbers can be written with scientific (exponent) notation:
This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63:
|Value (aka Fraction/Mantissa)||Exponent||Sign|
|52 bits (0 - 51)||11 bits (52 - 62)||1 bit (63)|
Integers (numbers without a period or exponent notation) are accurate up to 15 digits.
The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate:
To solve the problem above, it helps to multiply and divide:
Numbers are added. Strings are concatenated.
If you add two numbers, the result will be a number:
If you add two strings, the result will be a string concatenation:
If you add a number and a string, the result will be a string concatenation:
If you add a string and a number, the result will be a string concatenation:
A common mistake is to expect this result to be 30:
A common mistake is to expect this result to be 102030:
First 10 + 20 is added because x and y are both numbers.
Then 30 + "30" is concatenated because z is a string.
This will work:
This will also work:
And this will work:
But this will not work:
Trying to do arithmetic with a non-numeric string will result in
NaN (Not a Number):
However, if the string contains a numeric value , the result will be a number:
isNaN()) to find out if a value is a number:
Watch out for
NaN. If you use
NaN in a mathematical operation, the result will also be
Or the result might be a concatenation:
NaN is a number:
typeof NaN returns
Division by 0 (zero) also generates
Infinity is a number:
typeof Infinity returns
Never write a number with a leading zero (like 07).
But you can use the
toString() method to output numbers from base 2 to base 36.
Hexadecimal is base 16. Decimal is base 10. Octal is base 8. Binary is base 2.
var x = 123;
But numbers can also be defined as objects with the keyword
var y = new Number(123);
Do not create Number objects. It slows down execution speed.
new keyword complicates the code. This can produce some unexpected results:
When using the
== operator, equal numbers are equal:
When using the
=== operator, equal numbers are not equal, because the
=== operator expects equality in both type and value.
Or even worse. Objects cannot be compared:
Note the difference between (x==y) and (x===y).