Math Object
Math Object
Section titled βMath ObjectβWhat it means
Section titled βWhat it meansβThe built-in Math object provides constants and static methods for numeric operations β rounding, trigonometry, random numbers, min/max, and more. Unlike most JS objects, you never instantiate Math β you call its methods directly, e.g. Math.round(), not new Math().
Examples
Section titled βExamplesβconsole.log(Math.round(4.5)); // 5console.log(Math.floor(4.9)); // 4console.log(Math.ceil(4.1)); // 5console.log(Math.abs(-7)); // 7console.log(Math.max(3, 7, 2)); // 7console.log(Math.min(3, 7, 2)); // 2console.log(Math.pow(2, 10)); // 1024 (also: 2 ** 10)console.log(Math.sqrt(16)); // 4
// Random integer between min and max (inclusive)function randomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min;}console.log(randomInt(1, 6)); // simulates a dice rollCommon mistake
Section titled βCommon mistakeβAssuming Math.random() includes the upper bound, or forgetting Math.floor() when generating a random integer β Math.random() returns a float in [0, 1), so without flooring you get a float, and without the +1 adjustment your range excludes the max value.
// Bug: returns a float, not an integer, and never quite reaches `max`function randomInt(min, max) { return Math.random() * (max - min) + min;}
// Correct: floors to an integer and includes both min and maxfunction randomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min;}Quick practice
Section titled βQuick practiceβ-
What range of values does
Math.random()return?Answer
A float from0(inclusive) up to but not including1β[0, 1). -
Whatβs the difference between
Math.floor()andMath.round()for4.5?Answer
Math.floor(4.5)gives4(always rounds down);Math.round(4.5)gives5(rounds to the nearest integer, halves round up). -
How do you generate a random integer between 1 and 6 (inclusive), like a dice roll?
Answer
Math.floor(Math.random() * 6) + 1