JavaScript Math
The JavaScript `Math` object provides a variety of methods and properties for performing mathematical tasks. This guide covers the most commonly used Math methods and constants.
1. Math Constants
The `Math` object includes several useful constants:
- `Math.PI`
The value of π (pi), approximately 3.14159.
// Example of Math.PI
console.log(Math.PI); // 3.141592653589793
- `Math.E`
The value of e (Euler's number), approximately 2.71828.
// Example of Math.E
console.log(Math.E); // 2.718281828459045
2. Basic Math Methods
The `Math` object provides several methods for basic mathematical operations:
- `Math.round()`
Rounds a number to the nearest integer.
// Example of Math.round()
console.log(Math.round(4.7)); // 5
console.log(Math.round(4.4)); // 4
- `Math.ceil()`
Rounds a number up to the nearest integer.
// Example of Math.ceil()
console.log(Math.ceil(4.1)); // 5
- `Math.floor()`
Rounds a number down to the nearest integer.
// Example of Math.floor()
console.log(Math.floor(4.9)); // 4
- `Math.abs()`
Returns the absolute value of a number.
// Example of Math.abs()
console.log(Math.abs(-4.7)); // 4.7
- `Math.sqrt()`
Returns the square root of a number.
// Example of Math.sqrt()
console.log(Math.sqrt(16)); // 4
3. Trigonometric Methods
The `Math` object also provides methods for trigonometric calculations:
- `Math.sin()`
Returns the sine of a number (angle in radians).
// Example of Math.sin()
console.log(Math.sin(Math.PI / 2)); // 1
- `Math.cos()`
Returns the cosine of a number (angle in radians).
// Example of Math.cos()
console.log(Math.cos(0)); // 1
- `Math.tan()`
Returns the tangent of a number (angle in radians).
// Example of Math.tan()
console.log(Math.tan(Math.PI / 4)); // 1
4. Exponential and Logarithmic Methods
These methods handle exponential and logarithmic operations:
- `Math.exp()`
Returns e raised to the power of a number.
// Example of Math.exp()
console.log(Math.exp(1)); // 2.718281828459045
- `Math.log()`
Returns the natural logarithm (base e) of a number.
// Example of Math.log()
console.log(Math.log(10)); // 2.302585092994046
- `Math.pow()`
Returns the base to the exponent power.
// Example of Math.pow()
console.log(Math.pow(2, 3)); // 8
- `Math.sqrt()`
Returns the square root of a number.
// Example of Math.sqrt()
console.log(Math.sqrt(16)); // 4
5. Random Number Generation
The `Math` object can generate random numbers:
- `Math.random()`
Returns a pseudo-random number between 0 (inclusive) and 1 (exclusive).
// Example of Math.random()
console.log(Math.random()); // e.g., 0.732549162800805
- Generating a Random Integer within a Range
You can use `Math.random()` to generate a random integer within a specified range.
// Example of generating a random integer between min (inclusive) and max (exclusive)
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
console.log(getRandomInt(1, 10)); // e.g., 7