JavaScript provides a built-in Math object that contains useful properties and methods for performing mathematical operations.
You'll use it whenever you need to work with things like:
Rounding numbers
Finding the largest or smallest number
Calculating powers and square roots
Generating random numbers
Creating random values for games and applications
Let's see how it works.
The Math Object
The Math object is built into JavaScript, so we don't need to import anything.
For example:
console.log(Math.PI);Output:
3.141592653589793We can directly use methods from Math:
console.log(Math.sqrt(25));Output:
5Rounding Numbers
JavaScript provides several methods for rounding numbers.
Math.round()
Rounds a number to the nearest integer.
console.log(Math.round(4.4));
console.log(Math.round(4.6));Output:
4
5For example:
console.log(Math.round(10.5));Output:
11Math.floor()
Math.floor() always rounds down.
console.log(Math.floor(4.9));Output:
4Even:
console.log(Math.floor(4.1));gives:
4Math.ceil()
Math.ceil() always rounds up.
console.log(Math.ceil(4.1));Output:
5Even:
console.log(Math.ceil(4.9));gives:
5Math.trunc()
Math.trunc() simply removes the decimal part.
console.log(Math.trunc(4.9));
console.log(Math.trunc(4.1));Output:
4
4With negative numbers:
console.log(Math.trunc(-4.9));Output:
-4So the difference is:
Method |
| Purpose |
|---|---|---|
|
| Nearest integer |
|
| Round down |
|
| Round up |
|
| Remove decimal part |
Finding Minimum and Maximum
Math.max()
Returns the largest number.
console.log(Math.max(10, 50, 30, 20));Output:
50Math.min()
Returns the smallest number.
console.log(Math.min(10, 50, 30, 20));Output:
10We can also use them with an array by using the spread operator:
const numbers = [10, 50, 30, 20];
console.log(Math.max(...numbers));
console.log(Math.min(...numbers));Output:
50
10Absolute Value
Math.abs() returns the positive value of a number.
console.log(Math.abs(-10));Output:
10It can be useful when we only care about the distance between two values.
For example:
const difference = Math.abs(20 - 50);
console.log(difference);Output:
30Powers
We can calculate powers using Math.pow():
console.log(Math.pow(2, 3));Output:
8This means:
2³ = 8However, modern JavaScript usually uses the exponentiation operator **:
console.log(2 ** 3);Output:
8Square Root
Math.sqrt() calculates the square root.
console.log(Math.sqrt(25));Output:
5Another example:
console.log(Math.sqrt(81));Output:
9Random Numbers
Now let's look at one of the most useful features of the Math object: generating random numbers.
We use:
Math.random()It returns a pseudo-random decimal number between:
0 (inclusive) and 1 (exclusive)For example:
console.log(Math.random());You might get:
0.472819...Run it again and you'll get another value.
Random Integer Between 0 and 9
Math.random() gives decimals, but we often need whole numbers.
We can combine it with Math.floor():
const number = Math.floor(Math.random() * 10);
console.log(number);This generates:
0 to 9Why?
Math.random()
↓
0.0 to less than 1.0
× 10
↓
0 to less than 10
Math.floor()
↓
0 to 9Random Integer Between 1 and 10
To generate a number from 1 to 10:
const number = Math.floor(Math.random() * 10) + 1;
console.log(number);Possible results:
1
2
3
...
10The + 1 shifts the range from 0–9 to 1–10.
Random Integer in a Range
A very useful formula is:
Math.floor(Math.random() * (max - min + 1)) + minFor example, to generate a random number between 20 and 50:
const number = Math.floor(Math.random() * (50 - 20 + 1)) + 20;
console.log(number);The result will always be between 20 and 50.
We can make this reusable with a function:
function randomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomNumber(1, 100));Now we can generate random integers in any range.
Generating a Random Array Element
Random numbers become especially useful when working with arrays.
Suppose we have:
const fruits = ["Apple", "Banana", "Mango", "Orange"];We can select a random fruit:
const randomIndex = Math.floor(Math.random() * fruits.length);
console.log(fruits[randomIndex]);Possible output:
Mangoor:
Appleor any other element in the array.
This technique is commonly used in games, random quizzes, random recommendations, and many other applications.
A Practical Example: Dice Roll
Let's simulate a six-sided dice.
const dice = Math.floor(Math.random() * 6) + 1;
console.log(`You rolled: ${dice}`);Possible output:
You rolled: 4Every time you run the code, you'll get a value between 1 and 6.
We can turn it into a function:
function rollDice() {
return Math.floor(Math.random() * 6) + 1;
}
console.log(rollDice());Now we can call rollDice() whenever we need a new roll.
A Practical Example: Random Color
We can also generate random hexadecimal colors.
function randomColor() {
const number = Math.floor(Math.random() * 16777216);
return "#" + number.toString(16).padStart(6, "0");
}
console.log(randomColor());Possible output:
#3fa82cHere we're combining several concepts—random numbers, number conversion, and strings—to generate a random color.
Important Math Methods
Here are some of the methods you'll commonly use:
Method | Purpose |
|---|---|
| Round to nearest integer |
| Round down |
| Round up |
| Remove decimal part |
| Get absolute value |
| Find largest value |
| Find smallest value |
| Calculate square root |
| Calculate power |
| Generate pseudo-random number |
Conclusion
The JavaScript Math object gives us many useful tools for mathematical operations.
The most important ones to remember are:
Math.round()
Math.floor()
Math.ceil()
Math.min()
Math.max()
Math.abs()
Math.sqrt()
Math.random()And when working with random integers, remember this common pattern:
Math.floor(Math.random() * 10) + 1This generates a random integer from 1 to 10.
Once you understand Math.random(), you'll be able to build simple things like dice games, random quizzes, number games, random selections, and many other interactive features.