Lesson 8 of 156 ยท Data Types
The Math Object
Use the JavaScript Math object to round numbers, find minimums and maximums, generate random integers in a range, and calculate powers, roots and distances.
JavaScript's arithmetic operators handle adding, subtracting, multiplying and dividing. For everything else, such as rounding, square roots, random numbers or finding the largest value in a list, there's the built-in Math object.
Math isn't something you create. It's a ready-made toolbox of constants and functions that's always available, in every browser and in Node.js. You call its functions with a dot: Math.round(4.7). In this lesson you'll learn the functions you'll use most, plus a few practical recipes: rounding to decimal places, keeping a value in range, and picking random numbers.
Constants
Math holds a few mathematical constants. They're written in capitals because they never change:
Math.PI // 3.141592653589793 Math.E // 2.718281828459045, the base of natural logarithms Math.SQRT2 // 1.4142135623730951, the square root of 2
Math.PI is the one you'll actually use, for anything involving circles or angles:
const radius = 3; const area = Math.PI * radius ** 2; const circumference = 2 * Math.PI * radius;
Rounding
There are four ways to turn a decimal into a whole number, and they differ in which direction they go:
Math.round(x)rounds to the nearest integer. Halves (.5) round up, toward positive infinity.Math.floor(x)always rounds down, toward negative infinity.Math.ceil(x)always rounds up, toward positive infinity ("ceiling").Math.trunc(x)simply cuts off the decimal part, rounding toward zero.
For positive numbers, floor and trunc give the same result. The differences appear with negative numbers:
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Look closely at -4.5: Math.round() gives -4, not -5, because halves always round toward positive infinity. That's different from the "round half away from zero" rule many people learned at school. It rarely matters, but now you won't be surprised when it does.
Which one should you choose? Use round for "nearest", ceil when you need enough of something (how many boxes for 23 items, 10 per box? Math.ceil(23 / 10) is 3), and floor or trunc when you need complete units (how many full hours in 135 minutes? Math.floor(135 / 60) is 2).
Rounding to decimal places
Math.round() only rounds to whole numbers. To round to, say, two decimal places, scale up, round, then scale down:
const value = 3.14159; const rounded = Math.round(value * 100) / 100; // 3.14 (a number) const shown = value.toFixed(2); // "3.14" (a string)
Both approaches can be thrown off by the tiny binary errors you met in Numbers, so for money, keep values in cents and only format them for display.
Minimum and maximum
Math.min() and Math.max() take any number of arguments and return the smallest or largest:
Press Run (or Ctrl + Enter) to see the console output here.
No output.
The ... before the array is the spread syntax: it passes each item as a separate argument, as if you had typed Math.max(12.5, 18.1, ...). You'll learn it properly in Spread and Rest.
Math.max() with nothing to compare returns -Infinity, the "smallest possible starting point", so that any real number beats it. Likewise, Math.min() returns Infinity. If you see those values unexpectedly, you probably passed an empty array.
The clamp pattern is extremely common: keeping a volume between 0 and 100, a page number between 1 and the last page, or a game character inside the screen. If a value isn't a number at all, Math.max() and Math.min() return NaN, so validate your input first.
Absolute value and sign
Math.abs(x) returns the distance from zero, dropping any minus sign. Math.sign(x) tells you the direction: 1 for positive, -1 for negative and 0 for zero.
Math.abs(-7.5); // 7.5 Math.abs(3 - 10); // 7: the difference, whichever is bigger Math.sign(-42); // -1 Math.sign(0); // 0
Math.abs(a - b) is the standard way to ask "how far apart are these two numbers?", for example when checking whether a guess is close to the answer.
Powers and roots
Press Run (or Ctrl + Enter) to see the console output here.
No output.
x ** yraisesxto the powery. It's the modern operator, added in ES2016, and does the same asMath.pow(x, y).Math.sqrt()andMath.cbrt()give square and cube roots.Math.hypot(dx, dy)computes the length of the hypotenuse: the straight-line distance between two points. It saves you from writingMath.sqrt(dx ** 2 + dy ** 2).Math.log()is the natural logarithm;Math.log10()andMath.log2()use bases 10 and 2.
Random numbers
Math.random() returns a random decimal from 0 up to, but not including, 1. On its own that's not very useful, so you'll almost always scale it. Here's how the standard recipe for a random integer between min and max (both included) is built:
Math.random()gives a decimal in the range 0 to 0.999...- Multiply by the number of possible results,
max - min + 1. For a die (1 to 6), that's 6, giving 0 to 5.999... Math.floor()turns that into a whole number: 0 to 5.- Add
minto shift the range: 1 to 6.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Run it several times: the values change on every run. Two common mistakes to avoid:
- Using
Math.round()instead ofMath.floor(). Rounding makes the first and last values half as likely as the others, because they each get only half a "slot". - Forgetting the
+ 1. Without it,maxcan never come up.
For picking from an array, there's no + 1 because array.length is already the number of items, and the last index is length - 1.
Math.random() is not for security. Its numbers look random but are predictable to a determined attacker. For passwords, tokens or anything secret, use the Web Crypto API instead: crypto.getRandomValues() fills an array with secure random numbers, and crypto.randomUUID() creates a unique ID (it requires a secure HTTPS page). Both work in all modern browsers and in Node.js.
Trigonometry, briefly
Math also has sin, cos, tan, atan2 and friends, used for animations, games and graphics. They all work in radians, not degrees. A full circle is 2 * Math.PI radians, so convert like this:
const toRadians = (degrees) => degrees * (Math.PI / 180); Math.sin(toRadians(30)); // 0.49999999999999994, about 0.5
Note the tiny floating-point error again: round results before you show them.
Check your understanding
Quick check ยท 5 questions
of 5 answered You scored / 5 ยท perfect!
-
1. What does
Math.floor(-2.3)return?flooralways rounds down, toward negative infinity, so -2.3 becomes -3.Math.trunc(-2.3)would give -2. -
2. Which expression gives a random integer from 1 to 10, including both?
Math.random() * 10gives 0 to 9.99...,floormakes it 0 to 9, and+ 1shifts it to 1 to 10.Math.random()takes no arguments. -
3. How do you find the largest number in the array
nums?Math.max()expects separate arguments, so spread the array with.... Passing the array itself givesNaN. -
4. What is
Math.ceil(23 / 10), the number of 10-seat buses for 23 people?ceilrounds up, so 2.3 becomes 3. You need a third bus for the last three people. -
5. Which is the right tool for generating a secret password reset token?
Math.random()is predictable and must never be used for secrets. The Web Crypto API provides cryptographically secure random values.
Summary
Mathis a built-in object full of constants (Math.PI) and functions. You never create it; just callMath.something().- Round with
round(nearest),floor(down),ceil(up) ortrunc(toward zero). They differ for negative numbers. Math.min()andMath.max()take separate arguments; spread arrays with.... Combine them to clamp a value into a range.Math.abs()gives distance from zero;**,Math.sqrt(),Math.cbrt()andMath.hypot()handle powers, roots and distances.- For a random integer from
mintomax:Math.floor(Math.random() * (max - min + 1)) + min. - Never use
Math.random()for security; usecrypto.getRandomValues().
Next: Strings โ working with text.
Track your progress
Create a free account to tick off lessons and pick up where you left off on any device.
of JavaScript lessons completed