Sub topic 10
Meet the Math Object
Earlier chapters covered how JavaScript stores numbers and how its operators behave. JavaScript also has a built-in object called Math that collects constants and functions for numeric work. This chapter explains what kind of object Math is, which constants it provides, how its methods treat the arguments you pass, and which mistakes come up most often. The later chapters on rounding, extremes, powers, randomness, and trigonometry rely on this model.
This chapter assumes you can run JavaScript in a browser console or Node.js. It also assumes you know typeof, strict equality, and the special values NaN and Infinity from earlier chapters.
What Math Is, and What It Is Not
Math is a plain object that works as a namespace. It is not a class, and you never create instances of it. Every constant and function hangs directly off the object as a static property.
console.log(typeof Math); // "object"
console.log(Object.prototype.toString.call(Math)); // "[object Math]"
try {
new Math();
} catch (e) {
console.log(e instanceof TypeError); // true ("Math is not a constructor")
}
try {
Math();
} catch (e) {
console.log(e instanceof TypeError); // true ("Math is not a function")
}Compare this with Number and Date. Number is a function that converts values and also holds static helpers like Number.isInteger. Date is a constructor. Math is neither of these. It only holds properties.
| Built-in | Callable? | Constructible with `new`? | Main role |
|---|---|---|---|
| `Math` | No | No | Namespace of constants and numeric functions |
| `Number` | Yes, converts a value | Yes, but wrapper objects are rarely wanted | Conversion, plus validation helpers |
| `Date` | Yes, returns a string | Yes | Represents points in time |
| `BigInt` | Yes, converts a value | No | Arbitrary-precision integers |
Methods Are Ordinary Functions
Math methods do not use this, so you can pull them off the object and pass them around freely.
const { sqrt, PI } = Math;
console.log(sqrt(25)); // 5
console.log(PI); // 3.141592653589793
console.log([1, 4, 9].map(Math.sqrt)); // [ 1, 2, 3 ]The Constants
Math exposes eight constants. Each one is the closest double-precision value to the true mathematical constant.
| Constant | Meaning | Value |
|---|---|---|
| `Math.PI` | Ratio of a circle's circumference to its diameter | 3.141592653589793 |
| `Math.E` | Euler's number, the base of natural logarithms | 2.718281828459045 |
| `Math.LN2` | Natural log of 2 | 0.6931471805599453 |
| `Math.LN10` | Natural log of 10 | 2.302585092994046 |
| `Math.LOG2E` | Base-2 log of e | 1.4426950408889634 |
| `Math.LOG10E` | Base-10 log of e | 0.4342944819032518 |
| `Math.SQRT2` | Square root of 2 | 1.4142135623730951 |
| `Math.SQRT1_2` | Square root of 1/2 | 0.7071067811865476 |
The log constants are older than Math.log2 and Math.log10, and they still show up in legacy code. You will see expressions like Math.log(x) / Math.LN2 used to get a base-2 logarithm.
function circleArea(radius) {
return Math.PI * radius ** 2;
}
console.log(circleArea(2)); // 12.566370614359172
console.log(Math.LN2 === Math.log(2)); // true
console.log(Math.SQRT2 === Math.sqrt(2)); // trueConstants Cannot Be Changed
The constants are non-writable and non-configurable. If you assign to one in sloppy mode, the assignment is silently ignored. In strict mode, which covers modules and class bodies, the assignment throws.
"use strict";
console.log(Object.getOwnPropertyDescriptor(Math, "PI"));
// { value: 3.141592653589793, writable: false, enumerable: false, configurable: false }
try {
Math.PI = 3;
} catch (e) {
console.log(e instanceof TypeError); // true
}
console.log(Math.PI); // 3.141592653589793The methods are different. They are writable, so code can replace Math.random or Math.max. Test libraries sometimes do this on purpose to mock randomness. In application code, replacing them is a bug waiting to happen.
A Map of the Methods
The methods fall into a few families, and each family gets its own chapter later in this tutorial. This chapter covers the rules all the methods share.
The 32-bit helpers appear less often. Math.fround rounds a value to the nearest 32-bit float. Math.imul multiplies two values as 32-bit integers. Math.clz32 counts the leading zero bits of a 32-bit integer.
console.log(Math.fround(5.5)); // 5.5 (exactly representable in 32 bits)
console.log(Math.fround(5.05)); // 5.050000190734863
console.log(Math.imul(3, 4)); // 12
console.log(Math.clz32(1)); // 31How Math Methods Treat Arguments
Every Math method converts its arguments with the same ToNumber rules that Number() uses. As a result, the methods rarely throw. Bad input comes back as NaN.
console.log(Math.abs("-3")); // 3 (string converted)
console.log(Math.abs("3px")); // NaN
console.log(Math.abs(null)); // 0
console.log(Math.abs(undefined)); // NaN
console.log(Math.abs([])); // 0 ([] becomes "" becomes 0)
console.log(Math.abs([5])); // 5 ([5] becomes "5")
console.log(Math.abs([1, 2])); // NaN ("1,2" is not numeric)
console.log(Math.sqrt()); // NaN (missing argument is undefined)The silent coercion means a value read from a form can pass through Math without any error and come out as NaN several steps later. Validate input at the boundary with the Number.isFinite checks from the validation chapter. Don't count on Math to reject bad input.
BigInt is the one exception that throws. ToNumber refuses to convert a BigInt implicitly, so no Math method accepts one.
try {
Math.abs(-5n);
} catch (e) {
console.log(e instanceof TypeError); // true
}
console.log(Math.abs(Number(-5n))); // 5 (explicit conversion works)Extra Arguments Are Ignored, Except When They Are Not
Most methods read a fixed number of arguments and ignore any extras. Math.max, Math.min, and Math.hypot read all their arguments. This matters when you pass a method straight to Array.prototype.map, which calls the callback with (value, index, array).
console.log([1.4, 2.6].map(Math.round)); // [ 1, 3 ]
console.log(["1", "2", "3"].map(Math.max)); // [ NaN, NaN, NaN ]
console.log(["1", "2", "3"].map(Number)); // [ 1, 2, 3 ]In the second line, each call becomes something like Math.max("1", 0, ["1", "2", "3"]). The array argument converts to the string "1,2,3", then to NaN, and a single NaN argument makes the whole result NaN.
Precision Across Engines
Basic operations and Math.sqrt give the same correctly rounded result in every engine. The specification lets functions such as Math.sin, Math.exp, Math.log, and Math.pow be "implementation-approximated." In practice, Chrome, Firefox, Safari, and Node usually agree, but they can differ in the last digit for some inputs.
Common Errors
- Calling a constant:
Math.PI()throws a TypeError becauseMath.PIis a number. - Using
new Math():Mathis not a constructor. Call its methods directly. - Passing an array where a list is expected:
Math.max([3, 7])returnsNaN. Spread the array into separate arguments, as shown in the chapter on extremes. - Trusting coercion:
Math.floor("")returns0, which hides missing input. - Expecting degrees: trigonometric methods use radians.
- Mixing BigInt: convert explicitly with
Number(), and accept the possible loss of precision.
Exercises
Exercise
What do Math.sqrt("16"), Math.sqrt("16 "), and Math.sqrt("sixteen") return, and why?
Show answer
They return 4, 4, and NaN. Math methods convert arguments with the same rules as Number(). Number() trims surrounding whitespace, so "16 " becomes 16, but "sixteen" is not numeric and becomes NaN.
Exercise
A teammate writes const tops = scores.map(Math.max); to turn an array of numeric strings into numbers. Explain why every element becomes NaN and give a fix.
Show answer
map calls Math.max(value, index, array). Math.max reads all of its arguments, and the array converts to a string like "10,20" and then to NaN, which makes the result NaN. Use scores.map(Number), or scores.map(s => Math.max(Number(s))) if you need max for some other reason.
Exercise
In an ES module, what happens when you run Math.E = 3;? What happens when you run Math.random = () => 0.5;?
Show answer
Modules run in strict mode. Math.E is non-writable, so assigning to it throws a TypeError. Math.random is a writable method property, so the assignment succeeds and replaces the function for all code in that realm. Test frameworks do this to mock randomness, but it should not appear in application code.
Exercise
Write a function log2ViaConstants(x) that computes a base-2 logarithm using only Math.log and a Math constant. Name the built-in method that does this directly.
Show answer
function log2ViaConstants(x) { return Math.log(x) * Math.LOG2E; } You can also write Math.log(x) / Math.LN2. The built-in method is Math.log2, which is usually more accurate for exact powers of two.