AI Hints
Home›JavaScript Tutorial›Modules, Dates and Math
JavaScript · Lesson 78 of 138

Math and Random

Rounding and chance.

⏱ 2 min read▶ Video at 1:34:21🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

The Math object is a toolbox of maths functions. Rounding, square roots, the biggest of several numbers, and random numbers, for games and simulations.

Math and Random
From the video: Math and Random
  • A toolbox of maths
  • Rounding, roots, max
  • Random numbers

Math tools

Round, floor, and ceil round to the nearest, down, and up. Sqrt is the square root, and max and min find the extremes. Math dot random gives a decimal from zero up to one. To get a whole number from one to six, like a die, multiply by six, take the floor, and add one. Run it.

app.jsjavascript
console.log(Math.round(4.6), Math.floor(4.6), Math.ceil(4.2));
console.log(Math.sqrt(81), Math.max(3, 9, 2), Math.min(3, 9, 2));
console.log(Math.abs(-7), Math.PI.toFixed(4));

const roll = () => Math.floor(Math.random() * 6) + 1;
const rolls = Array.from({ length: 10 }, roll);
console.log("Rolls:", rolls.join(" "));
Output
5 4 5
9 9 2
7 3.1416
Rolls: 3 2 1 2 5 4 1 3 2 2

A note on random

Math dot random is fine for games and simple simulations. But it isn't safe for passwords or security tokens, because it can be predicted. For anything secret, use crypto dot random UUID, or crypto dot get random values. Array dot from, with a length, is a handy way to build arrays.

keyvalue
round / floor / ceilnearest, down, up
Math.random()0 up to 1
Dicefloor(random × 6) + 1
Securityuse crypto instead

Summary

The Math object rounds, finds extremes, and makes random numbers. Next, a new section, asynchronous JavaScript.

Key takeaways
  • Math.round / floor / ceil
  • Math.max / min
  • Math.random()
Next up: Synchronous and Asynchronous — waiting without blocking