The JavaScript Math.sqrt() method
The Math.sqrt() method returns the square root of a number. Math.sqrt(16) is 4. It returns NaN for negative numbers (no real square root). It's a staple of geometry — the Pythagorean distance between two points uses it.
Overview
Math.sqrt() gives the square root of a number — the value that, multiplied by itself, produces the input. Math.sqrt(25) is 5, Math.sqrt(2) is about 1.414. It's clearer and slightly faster than the equivalent Math.pow(x, 0.5).
Its signature use is the distance formula. The straight-line distance between two points is Math.sqrt(dx*dx + dy*dy) (Pythagoras) — the heart of hit detection, proximity checks and any "how far apart" calculation in games and graphics.
One thing to expect: the square root of a negative number isn't a real number, so Math.sqrt(-4) returns NaN. Guard against negative input if it's possible. For cube roots there's Math.cbrt(), and for other roots a fractional exponent with ** or Math.pow().
Syntax
Math.sqrt(x)
Math.sqrt(16) // 4
Math.sqrt(2) // 1.4142...
Math.sqrt(-4) // NaN
// distance between two points
Math.sqrt(dx * dx + dy * dy)
Parameters
The Math.sqrt() method accepts the following parameters.
| Parameter | Description |
|---|---|
x |
The number to take the square root of. Negative input returns NaN. |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const a = { x: 0, y: 0 }, b = { x: 3, y: 4 };
const dist = Math.sqrt((b.x - a.x) ** 2 + (b.y - a.y) ** 2);
document.getElementById('out').textContent =
'sqrt(16): ' + Math.sqrt(16) + '\n' +
'distance: ' + dist; // sqrt(16): 4 / distance: 5
</script>
Best practices
- Use
Math.sqrt()for the distance formula and geometry — it's clearer thanMath.pow(x, 0.5). - Guard against negative input, which returns
NaN. - Use
Math.cbrt()for cube roots and fractional exponents for other roots. - Compare squared distances when you only need to know which is larger — it skips the square root for speed.
Frequently asked questions
How do I get a square root in JavaScript?
Math.sqrt(x), e.g. Math.sqrt(9) is 3.Why does Math.sqrt() return NaN?
How do I calculate the distance between two points?
Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2).How do I get a cube root?
Math.cbrt(x), or a fractional exponent: x ** (1/3).