Math in JavaScript
In this tutorial, we will learn how to perform mathematical operations in JavaScript using the Math object.
The Math object in JavaScript provides a set of properties and methods for performing mathematical operations.
Basic Math Operations
The Math object provides several properties and methods for performing basic mathematical operations. Here are some of the most commonly used ones:
Math.PI
The Math.PI property represents the ratio of the circumference of a circle to its diameter, which is approximately 3.14159. You can use this property to calculate the area or circumference of a circle.
const radius = 5;
const area = Math.PI * radius * radius;
console.log(area); // 78.53981633974483Math.abs()
The Math.abs() method returns the absolute value of a number. It removes the sign of the number, if any, and returns the positive value.
const number = -10;
console.log(Math.abs(number)); // 10Math.round()
The Math.round() method rounds a number to the nearest integer. If the decimal part is .5 or greater, the number is rounded up; otherwise, it is rounded down.
const number = 3.7;
console.log(Math.round(number)); // 4Math.floor()
The Math.floor() method rounds a number down to the nearest integer. It always rounds the number down, even if the decimal part is .9.
const number = 3.9;
console.log(Math.floor(number)); // 3Math.ceil()
The Math.ceil() method rounds a number up to the nearest integer. It always rounds the number up, even if the decimal part is .1.
const number = 3.1;
console.log(Math.ceil(number)); // 4Random Numbers
The Math object provides methods for generating random numbers. Here are some of the most commonly used ones:
Math.random()
The Math.random() method returns a random floating-point number between 0 (inclusive) and 1 (exclusive).
const randomNumber = Math.random();
console.log(randomNumber); // Random number between 0 and 1Generating Random Integers
You can generate random integers within a specific range by combining Math.random() with other Math methods. Here is an example of generating a random integer between min and max (inclusive):
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const randomInt = getRandomInt(1, 10);
console.log(randomInt); // Random integer between 1 and 10Conclusion
- The
Mathobject in JavaScript provides a set of properties and methods for performing mathematical operations. - You can use the
Mathobject to perform basic math operations, generate random numbers, and more. - The
Mathobject is a built-in object in JavaScript, so you can use it without importing any external libraries.
How is this guide?
Sign in to share your feedback
Help us improve by sharing your thoughts on this guide.
Last updated on