JavaScript Math

Rounding, random numbers and maths functions.

✍️ 3 exercises + code challenge in this lesson

The Math object provides mathematical constants and functions:

  • Math.round(), Math.ceil(), Math.floor(), Math.trunc()
  • Math.max(), Math.min(), Math.abs()
  • Math.pow(), Math.sqrt()
  • Math.PI
  • Math.random(): a random number from 0 (inclusive) to 1 (exclusive).

A random integer between min and max: Math.floor(Math.random() * (max - min + 1)) + min

Key Takeaways: JavaScript Math

Mastering JavaScript Math helps you write clean and reliable JavaScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

JavaScript Math Code Example

JavaScript
<pre id="out"></pre>
<script>
const log = (...a) => document.getElementById("out").textContent += a.join(" ") + "\n";
log(Math.round(4.6), Math.ceil(4.1), Math.floor(4.9));
log("max:", Math.max(3, 9, 1), "min:", Math.min(3, 9, 1));
log("sqrt(64):", Math.sqrt(64), "PI:", Math.PI.toFixed(4));

const dice = () => Math.floor(Math.random() * 6) + 1;
log("Dice rolls:", dice(), dice(), dice());
</script>
<button onclick="location.reload()">Roll again</button>
Free sign-in required · Google login available

JavaScript Math Practice Exercises

Check what you learned in “JavaScript Math”.

/ 3 solved
Fill in the blank

Round the number down.

Math.(4.9)   // 4
✓ Correct! Not quite. Try again.
Multiple choice

What range does Math.random() return?

✓ Correct! Not quite. Try again.
Code challenge

Log the largest of 7, 42 and 13 using Math.max().

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services