The built-in Math namespace object provides static properties and functions for mathematical constants, rounding, trigonometric functions, powers, and roots. Math is not a constructor; all its methods are static.
flowchart TD
MathObj["Math Namespace"] --> Constants["Constants: Math.PI, Math.E"]
MathObj --> Rounding["Rounding: Math.round(), Math.floor(), Math.ceil(), Math.trunc()"]
MathObj --> MathOps["Math Operations: Math.pow(), Math.sqrt(), Math.abs(), Math.min(), Math.max()"]
| Method | Target Example | Result | Explanation |
|---|---|---|---|
Math.round(x) |
4.5 vs 4.4 |
5 vs 4 |
Rounds to nearest integer. |
Math.floor(x) |
4.9 vs -4.1 |
4 vs -5 |
Rounds downward toward negative infinity. |
Math.ceil(x) |
4.1 vs -4.9 |
5 vs -4 |
Rounds upward toward positive infinity. |
Math.trunc(x) |
4.9 vs -4.9 |
4 vs -4 |
Removes decimal fraction (truncates). |
// Demonstrating Math rounding, constants, and utilities
// 1. Math Constants
console.log(`Math.PI: ${Math.PI}`); // 3.141592653589793
// 2. Rounding Operations Comparison
const val = 4.7;
const negVal = -4.7;
console.log(`round(${val}): ${Math.round(val)}`); // 5
console.log(`floor(${val}): ${Math.floor(val)}`); // 4
console.log(`ceil(${val}): ${Math.ceil(val)}`); // 5
console.log(`trunc(${val}): ${Math.trunc(val)}`); // 4
console.log(`floor(${negVal}): ${Math.floor(negVal)}`); // -5
console.log(`trunc(${negVal}): ${Math.trunc(negVal)}`); // -4
// 3. Min, Max, and Absolute Values
const numbers = [15, 3, 99, 42, -8];
console.log(`Max value (Spread): ${Math.max(...numbers)}`); // 99
console.log(`Min value (Spread): ${Math.min(...numbers)}`); // -8
console.log(`Absolute value Math.abs(-50): ${Math.abs(-50)}`); // 50
// 4. Square Root and Powers
console.log(`Math.sqrt(64): ${Math.sqrt(64)}`); // 8
console.log(`Math.pow(2, 5): ${Math.pow(2, 5)}`); // 32
Math.max(): Math.max() accepts individual arguments (Math.max(1, 5, 3)). To pass an array, spread it: Math.max(...arr).Math.floor() vs Math.trunc() for Negative Numbers: Math.floor(-3.1) returns -4, whereas Math.trunc(-3.1) returns -3.Math Cannot Be Instantiated: Calling new Math() throws a TypeError.Calculate the hypotenuse of a right triangle with sides a = 6 and b = 8 using Math.hypot(a, b).
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.