The Math
object in JavaScript provides mathematical constants and functions. Itโs not a constructor, so you donโt use new Math()
. Just call its methods directly like Math.random()
or Math.floor()
.
Math.PI
โ 3.14159...Math.E
โ Eulerโs number (2.718...)Math.SQRT2
โ โ2console.log(Math.PI); // 3.141592653589793 console.log(Math.E); // 2.718281828459045
Math.round(x)
โ Nearest integerMath.floor(x)
โ Down to nearest integerMath.ceil(x)
โ Up to nearest integerMath.trunc(x)
โ Remove decimal partMath.round(4.7); // 5 Math.floor(4.7); // 4 Math.ceil(4.3); // 5 Math.trunc(4.9); // 4
Math.max(...)
โ Highest valueMath.min(...)
โ Lowest valueMath.pow(x, y)
โ x to the power yMath.sqrt(x)
โ Square rootMath.abs(x)
โ Absolute (positive) valueMath.max(5, 10, 15); // 15 Math.min(-2, 0, 4); // -2 Math.pow(2, 3); // 8 Math.sqrt(16); // 4 Math.abs(-7); // 7
Math.random()
returns a random number between 0 (inclusive) and 1 (exclusive).
Math.random(); // e.g., 0.7263521 // Random number between 1 and 100: Math.floor(Math.random() * 100) + 1;
// Simulate a 6-sided die roll let roll = Math.floor(Math.random() * 6) + 1; console.log("You rolled:", roll);
Math.random()
with Math.floor()
to create custom ranges.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!