</>
Skip to content
JavaScript lessons (27/64)

JavaScript — Math

The Math namespace

No instantiation — just call it:

Math.PI;      // 3.141592653589793
Math.E;       // 2.718…
Math.SQRT2;

Rounding — four flavors

Call4.5-4.5Meaning
Math.round5-4nearest
Math.floor4-5always down
Math.ceil5-4always up
Math.trunc4-4chop decimals

Negative-number differences between floor/trunc are a classic quiz trap.

Powers, roots, absolutes

Math.pow(2, 8);   // 256   (or 2 ** 8)
Math.sqrt(81);    // 9
Math.cbrt(27);    // 3
Math.abs(-10);    // 10
Math.sign(-7);    // -1 · 1 · 0 by sign
Math.hypot(3, 4); // 5    √(a²+b²)

Min / max (with spread for arrays)

Math.max(10, 20, 5);        // 20
const nums = [10, 30, 5];
Math.max(...nums);          // 30

Random recap

Math.random();                              // [0, 1)
function randInt(min, max) {                // inclusive both ends
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
randInt(1, 10);

Security: Math.random() is predictable. Tokens/passwords need crypto.getRandomValues().

Trig & logs

Math.sin(Math.PI / 2);   // 1     radians only!
const rad = deg => deg * Math.PI / 180;
Math.log10(100);         // 2
Math.log2(8);            // 3
Math.exp(1);             // e

Floating-point reminder

0.1 + 0.2;               // 0.30000000000000004
(12.3456).toFixed(2);    // "12.35" — STRING result!

Round before comparing; format at display.

Mini Practice

  1. Table of round/floor/ceil/trunc across positives and negatives.
  2. Array max/min via spread.
  3. randInt dice simulator; tally 600 rolls.
  4. deg↔rad converters; verify sin(90°)=1.
  5. Hypotenuse calculator.
  6. Demonstrate the 0.1+0.2 artifact and its toFixed fix.

Next: break →

Related Topics

Frequently Asked Questions about Math

What is Math in JavaScript?

Math is a fundamental concept in JavaScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Math?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Math.

Why is Math important in JavaScript?

Math is essential for JavaScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.