JavaScript Math
The Math object in JavaScript provides a set of built-in methods and properties for performing mathematical operations.
Here are some of the most commonly used methods and properties of the Math object:
The Math.abs(x)
This method returns the absolute value of a number.
As an example:
const num = -5;
const absNum = Math.abs(num);
console.log(absNum); // Output: 5
The Math.ceil(x)
This method returns the smallest integer greater than or equal to a number.
As an example:
const num = 3.14;
const ceilNum = Math.ceil(num);
console.log(ceilNum); // Output: 4
The Math.floor(x)
This method returns the largest integer less than or equal to a number.
As an example:
const num = 3.14;
const floorNum = Math.floor(num);
console.log(floorNum); // Output: 3
The Math.max(x, y, ...)
This method returns the largest of the given numbers.
As an example:
const num1 = 5;
const num2 = 10;
const num3 = 15;
const maxNum = Math.max(num1, num2, num3);
console.log(maxNum); // Output: 15
The Math.min(x, y, ...)
This method returns the smallest of the given numbers.
As an example:
const num1 = 5;
const num2 = 10;
const num3 = 15;
const minNum = Math.min(num1, num2, num3);
console.log(minNum); // Output: 5
The Math.pow(x, y)
This method returns the result of raising x to the power of y.
As an example:
const num1 = 2;
const num2 = 3;
const powNum = Math.pow(num1, num2);
console.log(powNum); // Output: 8
The Math.round(x)
This method returns the value of a number rounded to the nearest integer.
As an example:
const num = 3.5;
const roundNum = Math.round(num);
console.log(roundNum); // Output: 4
The Math.sqrt(x)
This method returns the square root of a number.
As an example:
const num = 25;
const sqrtNum = Math.sqrt(num);
console.log(sqrtNum); // Output: 5
The Math.random()
This method returns a random number between 0 and 1.
As an example:
const randomNum = Math.random();
console.log(randomNum); // Output: a random number between 0 and 1