JavaScript has only one type of number. Numbers can be written with or without decimals. Unlike many other programming languages, JavaScript does not define different types of numbers like integers, short, long, or floating-point.
Numbers in JavaScript can be written in several ways:
let x = 3.14; // A number with decimals
let y = 3; // A number without decimals
let z = 123e5; // 12300000
let w = 123e-5; // 0.00123
Integers (numbers without a period) are accurate up to 15 digits. However, floating-point arithmetic is not always 100% accurate.
let x = 0.1 + 0.2;
console.log(x); // Result: 0.30000000000000004
WARNING: JavaScript uses the + operator for both addition and concatenation.
let x = 10;
let y = "20";
let result = x + y; // "1020" (concatenation)
NaN is a JavaScript reserved word indicating that a number is not a legal
number. Trying to do arithmetic with a non-numeric string will result in NaN.
let x = 100 / "Apple";
console.log(x); // NaN
You can use the global isNaN() function to check if a value is not a number.
Infinity (or -Infinity) is the value JavaScript returns if you
calculate a number outside the largest possible number allowed.
let x = 2 / 0; // Infinity
let y = -2 / 0; // -Infinity
console.log(typeof Infinity); // "number"
NaN is used to represent an "illegal" number resultInfinity is a number that occurs when dividing by zerotypeof to verify that a value is numeric