| Strings & Template Literals | Conversion & Coercion in JavaScript | |
JavaScript Numbers & Math Object |
JavaScript has only one type of number: double-precision 64-bit floating point (same as IEEE 754 standard). It can represent both integers and decimals.
let x = 10; // integer
let y = 3.14; // floating point
let z = 2e5; // scientific notation (200000)
let big = 999999999999999; // precision limit (15 digits)
let notANum = "abc" / 2; // NaN (Not a Number)
let inf = 1 / 0; // Infinity
// Operations
console.log(10 + 5); // 15
console.log(10 - 5); // 5
console.log(10 * 5); // 50
console.log(10 / 3); // 3.3333333333333335
console.log(10 % 3); // 1 (remainder)
Infinity β result of division by zero-Infinity β negative division by zeroNaN β Not a Number (invalid operations)console.log(1 / 0); // Infinity
console.log(-1 / 0); // -Infinity
console.log("abc" / 2); // NaN
Numbers come with useful methods:
let num = 123.456;
console.log(num.toFixed(2)); // "123.46" (rounds to 2 decimals)
console.log(num.toString()); // "123.456" (convert to string)
console.log(Number("42")); // 42 (convert string to number)
console.log(parseInt("12.34")); // 12
console.log(parseFloat("12.34")); // 12.34
The Math object provides properties and methods for mathematical operations. It is static, so you donβt create it with new.
console.log(Math.PI); // 3.141592653589793 console.log(Math.E); // 2.718281828459045 console.log(Math.SQRT2); // 1.4142135623730951
Math.round(x) β Round to nearest integerMath.ceil(x) β Round upMath.floor(x) β Round downMath.trunc(x) β Remove decimal partMath.pow(x, y) β x to the power yMath.sqrt(x) β Square rootMath.abs(x) β Absolute valueMath.min(...values) β Smallest valueMath.max(...values) β Largest valueMath.random() β Random number between 0 and 1console.log(Math.round(4.6)); // 5 console.log(Math.ceil(4.1)); // 5 console.log(Math.floor(4.9)); // 4 console.log(Math.trunc(4.9)); // 4 console.log(Math.pow(2, 3)); // 8 console.log(Math.sqrt(64)); // 8 console.log(Math.abs(-7)); // 7 console.log(Math.min(3, 7, 1)); // 1 console.log(Math.max(3, 7, 1)); // 7 console.log(Math.random()); // random between 0 and 1
let radius = 5;
let area = Math.PI * Math.pow(radius, 2);
console.log("Area of circle: " + area);
Generate a random integer between 1 and 10:
let randomNum = Math.floor(Math.random() * 10) + 1;
console.log("Random number: " + randomNum);
NaN, Infinity, -Infinity.Math object provides constants and methods for calculations.Math.random() with Math.floor() to generate random integers. | Strings & Template Literals | Conversion & Coercion in JavaScript | |