Learn JavaScript
❯ types.math_object

Math Object Essentials in JavaScript

$concept

Math is a namespace of constants and pure functions — not a constructor, never instantiated. Essentials: Math.round/floor/ceil/trunc (four rounding modes), Math.abs/max/min (spread for arrays: Math.max(...arr)), Math.pow/sqrt/cbrt, Math.random for [0,1) floats, and Math.trunc for toward-zero integer parts.

random() needs scaling for ranges (Math.floor(Math.random() * 6) + 1 for dice) and is NOT cryptographic — crypto.getRandomValues serves security needs. Constants Math.PI/E round out geometry and logarithms (Math.log is natural log).

$how it works
1

Four roundings

round (nearest, halves up), floor (down), ceil (up), trunc (toward zero) — distinct tools, not synonyms.

2

max/min with spread

Math.max(...arr) spreads arrays into arguments — empty arrays give -Infinity/Infinity, guard them.

3

Scaled randoms

Math.floor(Math.random() * n) yields 0..n-1 uniformly — the dice-roll formula to memorize.

4

Not for secrets

Math.random is predictable — tokens, salts, and draws use crypto.getRandomValues instead.

$example
console.log(Math.floor(3.9), Math.ceil(3.1));
console.log(Math.max(3, 9, 4));
console.log(Math.floor(Math.random() * 6) + 1 >= 1);
Output
3 4
9
true
1floor drops to 3, ceil lifts to 4 — directional rounding demonstrated.
2max picks 9 from discrete arguments.
3The dice formula always yields 1–6 here — true confirms the range holds.
$use cases
Rounding modes chosen per domain (bills vs pixels vs stats)
Dice rolls and shuffles with scaled Math.random
Max/min over arrays via spread (with empty-array guards)
Crypto-grade randomness exclusively from getRandomValues

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.