The JavaScript Math object provides a set of properties and methods for performing mathematical operations in JavaScript.
These include basic math functions like addition, subtraction, multiplication, and division, as well as more advanced functions like exponentiation and finding the square root. By using the Math object, you can perform complex math operations in your JavaScript programs with ease.
Here are some of the commonly used properties and methods of the Math object:
- Math.PI – This property represents the value of pi, which is approximately 3.141592653589793.
- Math.abs(x) – This method returns the absolute value of x.
- Math.ceil(x) – This method returns the smallest integer greater than or equal to x.
- Math.floor(x) – This method returns the largest integer less than or equal to x.
- Math.round(x) – This method returns the value of x rounded to the nearest integer.
- Math.max(x,y,z,…) – This method returns the largest of the specified numbers.
- Math.min(x,y,z,…) – This method returns the smallest of the specified numbers.
- Math.random() – This method returns a random number between 0 and 1.
- Math.sqrt(x) – This method returns the square root of x.
- Math.pow(x,y) – This method returns the value of x to the power of y.
JavaScript Math Object example
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
// Generate a random number between 1 and 10
const randomNumber = Math.floor(Math.random() * 10) + 1;
// square root of the random number
const squareRoot = Math.sqrt(randomNumber);
// Display the results
console.log(`The random number is: ${randomNumber}`);
console.log(`The square root is: ${squareRoot}`);
</script>
</body>
</html>
Output:
Do comment if you have any doubts or suggestions on this JS object topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version