JavaScript Tutorial
JavaScript Math
Math.round, floor, ceil, max, min, and abs sit on the Math object. There is no math module to import.
Math is already there
Python starts with import math. JavaScript does not. Math is a built-in object on the global scope. Call Math.round(n) from any script in the browser.
You never write new Math(). The functions live on the object itself. Constants such asMath.PI live there too.
Try the calls in /javascript/try. Change the inputs. The Python editor at/try will not run this.
round, floor, and ceil
Math.round(n) goes to the nearest integer. Halfway cases such as 2.5 round toward +Infinity, so 2.5 becomes 3.
Math.floor(n) goes down (toward −Infinity). Math.ceil(n) goes up (toward +Infinity). For positive numbers, floor chops the fraction and ceil takes the next integer if any fraction exists.
Example
console.log(Math.round(2.3));
console.log(Math.round(2.7));
console.log(Math.floor(2.7));
console.log(Math.ceil(2.1));
console.log(Math.floor(-1.2));
document.body.textContent =
Math.round(2.7) + " " + Math.floor(2.7) + " " + Math.ceil(2.1);
max and min
Math.max(a, b, ...) returns the largest argument. Math.min returns the smallest. Pass as many numbers as you need. With no arguments, max is -Infinity andmin is Infinity.
To rank an array, spread is not required yet: Math.max.apply(null, list) works, or loop and keep a running best. Empty lists are a special case — do not call max on nothing by accident.
Example
const scores = [88, 41, 95, 70];
const high = Math.max(88, 41, 95, 70);
const low = Math.min(88, 41, 95, 70);
console.log(high);
console.log(low);
console.log(Math.max(0, high));
document.body.textContent = "high " + high + " / low " + low;
abs, pow, and sqrt
Math.abs(n) drops the sign: negative becomes positive. Use it for distances and differences.Math.pow(base, exp) raises a power. base ** exp is the same idea with an operator.Math.sqrt(n) is the square root.
Example
console.log(Math.abs(-12));
console.log(Math.pow(2, 8));
console.log(2 ** 8);
console.log(Math.sqrt(9));
const a = 3;
const b = 4;
const c = Math.sqrt(a * a + b * b);
console.log(c);
document.body.textContent = "hypot " + c;
The usual toolkit
| Call | Meaning |
|---|---|
Math.round(n) | Nearest integer |
Math.floor(n) | Integer toward −Infinity |
Math.ceil(n) | Integer toward +Infinity |
Math.max(a, b) | Larger value |
Math.min(a, b) | Smaller value |
Math.abs(n) | Absolute value |
Math.PI | Pi, about 3.14159 |
Rounding for display is often Number(n.toFixed(2)) from the number-methods chapter, notMath.round. round has no “decimal places” argument.
What to remember
- No import. Call
Math.method(...)directly. - floor goes down, ceil goes up, round goes to nearest.
maxandmintake separate arguments, not one array, in the basic form.- Do not write
new Math().
Next: random numbers — scale a float in [0, 1) into an integer range.