On this page
Math in JavaScript
The Math
object in JavaScript is a built-in object that has properties and methods for mathematical constants and functions. It’s not a constructor, so you don’t create instances of the Math
object. Instead, you use its properties and methods directly.
Common Properties
- Math.PI: The ratio of the circumference of a circle to its diameter, approximately 3.14159.
console.log(Math.PI); // 3.141592653589793
Common Methods
- Math.abs(x): Returns the absolute value of a number.
console.log(Math.abs(-5)); // 5
- Math.ceil(x): Rounds a number up to the next largest integer.
console.log(Math.ceil(4.2)); // 5
- Math.floor(x): Rounds a number down to the next smallest integer.
console.log(Math.floor(4.8)); // 4
- Math.round(x): Rounds a number to the nearest integer.
console.log(Math.round(4.5)); // 5
- Math.max(x, y, z, …): Returns the largest of the zero or more numbers given as input parameters.
console.log(Math.max(1, 2, 3)); // 3
- Math.min(x, y, z, …): Returns the smallest of the zero or more numbers given as input parameters.
console.log(Math.min(1, 2, 3)); // 1
- Math.pow(base, exponent): Returns the base to the exponent power, that is, base^exponent.
console.log(Math.pow(2, 3)); // 8
- Math.sqrt(x): Returns the positive square root of a number.
console.log(Math.sqrt(16)); // 4
- Math.random(): Returns a pseudo-random number between 0 (inclusive) and 1 (exclusive).
console.log(Math.random()); // e.g., 0.123456789
- Math.trunc(x): Returns the integer part of a number by removing any fractional digits.
console.log(Math.trunc(4.9)); // 4
Examples of Using Math Methods
- Calculating the Hypotenuse of a Right Triangle:
let a = 3;
let b = 4;
let c = Math.sqrt(Math.pow(a, b) + Math.pow(b, b));
console.log(c); // 5
- Generating a Random Number Between 1 and 10:
Copy code
let randomNum = Math.floor(Math.random() * 10) + 1;
console.log(randomNum); // random number between 1 and 10
- Rounding a Number to 2 Decimal Places:
let num = 5.6789;
let rounded = Math.round(num * 100) / 100;
console.log(rounded); // 5.68
- Finding the Maximum and Minimum Values in an Array:
let arr = [1, 2, 3, 4, 5];
let max = Math.max(...arr);
let min = Math.min(...arr);
console.log(`Max: ${max}, Min: ${min}`); // Max: 5, Min: 1
- Converting Degrees to Radians:
function degreesToRadians(degrees) {
return degrees * (Math.PI / 180);
}
console.log(degreesToRadians(90)); // 1.5707963267948966 (which is PI/2)