Math.sqrt()
Math.sqrt(x) The Math.sqrt() function returns the square root of a number — the value that, when multiplied by itself, equals the input. For negative inputs it returns NaN, since real square roots of negative numbers are undefined. For 0 it returns 0, and for Infinity it returns Infinity.
The function operates on 64-bit IEEE 754 double-precision floats, which is JavaScript’s native number format. Results are accurate to within one unit in the last place (ULP) for most inputs.
Syntax
Math.sqrt(x)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| x | Number | required | A non-negative number whose square root is to be computed |
Return value
The square root of x. Returns NaN if x is negative. Returns 0 if x is 0.
Examples
Basic usage
Math.sqrt(9);
// 3
Math.sqrt(2);
// 1.4142135623730951
Math.sqrt(1);
// 1
Math.sqrt(0);
// 0
The examples above show how Math.sqrt() handles typical values. The function also has well-defined behavior for edge cases — negative numbers, special IEEE 754 values, and scenarios where you might want a different kind of root.
Negative input returns NaN
Passing a negative number to Math.sqrt() returns NaN because no real number multiplied by itself produces a negative value. The square root of a negative number is an imaginary number, which lies outside the real number line. JavaScript handles this by returning NaN rather than throwing an error, so you can check the result instead of validating the input beforehand.
Math.sqrt(-1);
// NaN
Math.sqrt(-Infinity);
// NaN
To get the magnitude of a negative number, take the square root of its absolute value using Math.abs() first. This pattern is common when you need the Euclidean distance of a single coordinate regardless of sign.
Special values
Math.sqrt() also handles the special IEEE 754 floating-point values consistently. Infinity stays infinite because the square root of an infinitely large number is still infinite, and NaN propagates through the operation — any computation involving NaN produces NaN. These behaviors let you chain Math.sqrt() calls without explicit guard checks.
Math.sqrt(Infinity);
// Infinity
Math.sqrt(NaN);
// NaN
Pythagorean theorem
Beyond simple square root calculations, Math.sqrt() is the foundation for computing distances and magnitudes — the most common geometric use case in programming. The Pythagorean theorem states that the hypotenuse of a right triangle equals the square root of the sum of squared legs, and this formula generalizes to any number of dimensions.
function hypotenuse(a, b) {
return Math.sqrt(a ** 2 + b ** 2);
}
console.log(hypotenuse(3, 4));
// 5
console.log(hypotenuse(5, 12));
// 13
Note that Math.hypot(a, b) does the same thing with better numerical stability for very large or very small inputs, since it avoids intermediate overflow and underflow.
Common patterns
The Pythagorean pattern extends naturally to multi-dimensional distance calculations, input validation, and vector mathematics. Each pattern below builds on the basic square-root-plus-squared-sum formula, adding a practical concern that arises in real code.
Distance between two points
The distance formula generalizes the Pythagorean theorem to find the straight-line distance between any two points in 2D space. Subtract corresponding coordinates, square the differences, sum them, and take the square root of the result.
function distance(x1, y1, x2, y2) {
return Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
}
console.log(distance(0, 0, 3, 4));
// 5
console.log(distance(1, 1, 4, 5));
// 5
Safe sqrt (guard against negatives)
When your input might be negative — for example, from a subtraction that underflows or a sensor reading prone to noise — you should guard against NaN results. The safeSqrt wrapper explicitly returns NaN for negative inputs, making the behavior visible and testable. The magnitudeSqrt variant uses Math.abs() to silently convert negatives to positives, which is appropriate when only the magnitude matters.
function safeSqrt(x) {
if (x < 0) return NaN;
return Math.sqrt(x);
}
// Or use Math.abs for magnitude:
function magnitudeSqrt(x) {
return Math.sqrt(Math.abs(x));
}
console.log(magnitudeSqrt(-16));
// 4
Normalising a vector
Normalizing a vector means scaling its components so that the vector has a length of exactly 1 while preserving its direction. The process divides each component by the vector’s magnitude, which is computed as the square root of the sum of squared components. This operation is fundamental in 3D graphics for lighting calculations, in physics simulations for direction-only vectors, and in machine learning for feature scaling.
function normalize(vector) {
const magnitude = Math.sqrt(vector.reduce((sum, v) => sum + v ** 2, 0));
return vector.map(v => v / magnitude);
}
console.log(normalize([3, 4]));
// [0.6, 0.8]
Normalizing vectors to unit length (magnitude 1) is fundamental in 3D graphics, physics simulations, and machine learning. The magnitude is computed as the square root of the sum of squared components.
Checking if a number is a perfect square
A perfect square is an integer whose square root is also an integer. Checking this is a two-step process: compute the square root, then verify it is a whole number using Number.isInteger(). This test appears in number theory algorithms, puzzle solvers, and anywhere you need to determine whether a value is the square of some whole number.
function isPerfectSquare(n) {
if (n < 0) return false;
const root = Math.sqrt(n);
return Number.isInteger(root);
}
console.log(isPerfectSquare(25)); // true
console.log(isPerfectSquare(26)); // false
Math.sqrt() vs the exponent operator
Math.sqrt(x) and x ** 0.5 compute the same value, but Math.sqrt is generally preferred for clarity and may be slightly faster because the engine can recognise it as a single hardware instruction. The exponentiation operator is more flexible — you can use it for any fractional exponent — but for the specific case of square roots, Math.sqrt() signals intent more clearly to anyone reading the code.
Math.sqrt(16); // 4
16 ** 0.5; // 4 (same result)
(-16) ** 0.5; // NaN (same as Math.sqrt(-16))
Cube roots and higher roots
For cube roots, use Math.cbrt(x), which handles negative numbers correctly (the cube root of -8 is -2, not NaN). For other fractional exponents, use the ** operator. Note the important difference: Math.cbrt(-8) returns -2, but (-8) ** (1/3) returns NaN because the ** operator cannot handle a negative base with a fractional exponent. This mismatch is a common source of bugs when computing roots.
Math.cbrt(-8); // -2 (correct)
(-8) ** (1/3); // NaN (incorrect — fractional exponent with negative base)
Math.cbrt(27); // 3
27 ** (1/3); // 3 (works for positive bases)
The mismatch between ** and Math.cbrt for negative bases is a common source of bugs when computing roots.
Accuracy
Math.sqrt is required by the ECMAScript specification to return the correctly-rounded result — the closest representable 64-bit float to the true square root. This is a stronger guarantee than most other Math functions, which only need to be “implementation-dependent.” You can rely on Math.sqrt(x * x) returning exactly x for small integers.
See Also
- Math.pow() — raises a number to a given power
- Math.floor() — rounds down to the nearest integer
- Math.ceil() — rounds up to the nearest integer
- Math.abs() — returns the absolute value of a number