All technological notes.
JavaScript has only one type of number. Numbers can be written with or without decimals.
let x = 123e5; // 12300000
let y = 123e-5; // 0.00123
JavaScript Numbers are Always 64-bit Floating Point
Integer Precision
Integers (numbers without a period or exponent notation) are accurate up to 15 digits.
The maximum number of decimals is 17.
Floating Precision
let x = (0.2 * 10 + 0.1 * 10) / 10;
NaN - Not a NumberNaN
NaN is a number:
typeof NaN returns number.isNaN():
Computation:
NaN in a mathematical operation, the result will also be NaN or be a concatenation.var x = 100 / "Apple"; //x is NaN
console.log(x); //NaN
console.log(typeof x); //number
console.log(isNaN(x)); //true
var x = 100 / "10";
console.log(x); //10
console.log(isNaN(x)); //false
var x = NaN;
var y = 5;
console.log(x + y); //NaN
var x = NaN;
var y = "5";
console.log(x + y); //NaN5
InfinityInfinity (or -Infinity)
Infinity is a number:
typeof Infinity returns number.Division by 0 (zero) also generates Infinity.
isFinite():
var x = 2;
while (x != Infinity) {
// while (isFinite(x)) {
console.log(x);
x **= 2;
}
// 2
// 4
// 16
// 256
// 65536
// 4294967296
// 18446744073709552000
// 3.402823669209385e+38
// 1.157920892373162e+77
// 1.3407807929942597e+154
var y = 2 / 0;
console.log(y); //Infinity
console.log(typeof Infinity); //number
console.log(isFinite(y)); //false
console.log(y == Infinity); //true
numbers can also be defined as objects with the keyword new.
Do not create Number objects.
The new keyword complicates the code and slows down execution speed.
Number Objects can produce unexpected results
var x = 500;
var y = new Number(500);
var z = new Number(500);
console.log(x == y); //true
console.log(x === y); //false
console.log(y == z); //false
console.log(y === z); //false
JavaScript interprets numeric constants as hexadecimal if they are preceded by 0x.
By default, JavaScript displays numbers as base 10 decimals.
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 = 0xff;
console.log(x); //255
console.log(x.toString(2)); //11111111
console.log(x.toString(8)); //377
console.log(x.toString(10)); //255
console.log(x.toString(16)); //ff
console.log(x.toString(32)); //7v
+ operator for both addition and concatenation.| Operand 1st | Operand 2nd | Result |
|---|---|---|
| Number | Number | Number |
| String | String | Concatenation |
| Number | String | Concatenation |
| String | Number | Concatenation |
Numeric Strings
let x = "100";
let y = "10";
var z = x / y; //10
var z = x * y; //1000
var z = x - y; //90
var z = x + y; //"10010"