The Math Object: A Calculator in Your Pocket

Grade 3, page 8 of 11. A two-minute read.

JavaScript comes with a built-in toolbox called Math, packed with useful math functions. You use them by writing Math. followed by the tool's name.

Rounding numbers

JavaScript
console.log(Math.round(4.5));
console.log(Math.round(4.4));
console.log(Math.floor(4.9));
console.log(Math.ceil(4.1));
console.log(Math.trunc(-4.7));

It prints

5
4
4
5
-4
MethodWhat it doesMemory trick
Math.round(x)Rounds to the nearest whole numberNormal rounding
Math.floor(x)Always rounds downThe floor is down below
Math.ceil(x)Always rounds upThe ceiling is up above
Math.trunc(x)Chops off the decimal part"Truncate" means "cut short"

Other handy tools

JavaScript
console.log(Math.max(4, 19, 7, 2));
console.log(Math.min(4, 19, 7, 2));
console.log(Math.abs(-15));
console.log(Math.sqrt(81));
console.log(Math.PI);

It prints

19
2
15
9
3.141592653589793
  • Math.max(...) and Math.min(...) find the biggest and smallest of any numbers you give them.
  • Math.abs(x) gives the absolute value, which means it removes the minus sign. Useful for "how far apart are these two numbers?"
  • Math.sqrt(x) gives the square root.
  • Math.PI is the number π. (Note: no parentheses! It's a value, not an action.)

Random numbers

Now for the fun one. Math.random() gives you a random decimal number between 0 (included) and 1 (not included). Every time you call it, you get a different number:

JavaScript
console.log(Math.random());
console.log(Math.random());

Output

0.7341858224108491
0.0286427493216813

(Your numbers will be different. That's the whole point!)

A random decimal between 0 and 1 isn't very useful on its own. But with a bit of math, we can turn it into a random whole number in any range we like. Here's how to simulate rolling a six-sided die:

JavaScript
const roll = Math.floor(Math.random() * 6) + 1;
console.log(roll);

Let's walk through it, step by step:

  1. Math.random() gives a number from 0 up to (but not including) 1, like 0.734.
  2. * 6 stretches it to a number from 0 up to (but not including) 6, like 4.404.
  3. Math.floor(...) rounds down to a whole number from 0 to 5, like 4.
  4. + 1 shifts it to a number from 1 to 6, like 5. 🎲
TipThe random number recipe

To get a random whole number from 1 to max:

JavaScript
Math.floor(Math.random() * max) + 1

Want a number from 1 to 100? Use max = 100. A coin flip? Use max = 2 (and say 1 is heads, 2 is tails). Bookmark this page. You'll come back to this recipe again and again for games.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning