freecoding.school100% FREE · NO SIGNUP
Closure CavesISSUE #30 of 61

math · floor · ceil · round · random

LambdaVSThe Mutator
Lambda saysThe Math object has rounding, random, min/max, powers, and trig helpers.

Math.floor/ceil/round/trunc handle rounding; Math.random() gives a float in [0,1); Math.min/max compare; Math.abs/pow/sqrt and trig round it out. The classic idiom for a random integer in a range: Math.floor(Math.random() * (max - min + 1)) + min.

Power-ups you unlock

The Mutator attacks — common mistakes

Boss battleWrite a function that returns a random integer between two bounds inclusive.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><pre id="o"></pre>
<script>const rand=(min,max)=>Math.floor(Math.random()*(max-min+1))+min;
document.getElementById('o').textContent='roll: '+[rand(1,6),rand(1,6),rand(1,6)].join(' ');</script></body></html>
▶ Open the interactive comic issue
‹ Date Methods · Format · Parse · ArithmeticRegex · Pattern Matching ›