Js Math in JavaScript
? JavaScript Math Object
The Math object in JavaScript provides built-in properties and methods for mathematical constants and functions. It’s not a function, but a static object you can use directly.
? Common Math Properties
| Property | Description | Example |
|---|---|---|
Math.PI | ? (pi) constant | 3.141592653589793 |
Math.E | Euler’s number (e) | 2.718281828459045 |
Math.LN2 | Natural log of 2 | 0.6931471805599453 |
Math.LN10 | Natural log of 10 | 2.302585092994046 |
Math.SQRT2 | Square root of 2 | 1.4142135623730951 |
? Common Math Methods
| Method | Description | Example |
|---|---|---|
Math.abs(x) | Absolute value | Math.abs(-5); // 5 |
Math.round(x) | Rounds to nearest integer | Math.round(4.7); // 5 |
Math.floor(x) | Rounds down (floor) | Math.floor(4.7); // 4 |
Math.ceil(x) | Rounds up (ceiling) | Math.ceil(4.1); // 5 |
Math.max(a, b, ...) | Returns max of arguments | Math.max(3, 7, 2); // 7 |
Math.min(a, b, ...) | Returns min of arguments | Math.min(3, 7, 2); // 2 |
Math.pow(x, y) | x raised to the power y | Math.pow(2, 3); // 8 |
Math.sqrt(x) | Square root | Math.sqrt(16); // 4 |
Math.random() | Returns random float between 0-1 | Math.random(); // e.g., 0.234 |
Math.sin(x) | Sine of x (x in radians) | Math.sin(Math.PI / 2); // 1 |
Math.cos(x) | Cosine of x | Math.cos(0); // 1 |
? Example: Random Integer Between Two Values
function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); // The maximum and minimum are inclusive return Math.floor(Math.random() * (max - min + 1)) + min;}console.log(getRandomInt(1, 10)); // random int between 1 and 10Would you like me to show examples for any specific Math methods or formulas?