References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript Math.sqrt() method

Method JavaScript All modern browsers Updated
Quick answer

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

Live 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 than Math.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?
Use Math.sqrt(x), e.g. Math.sqrt(9) is 3.
Why does Math.sqrt() return NaN?
Because the input is negative — negative numbers have no real square root.
How do I calculate the distance between two points?
Use Pythagoras: Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2).
How do I get a cube root?
Use Math.cbrt(x), or a fractional exponent: x ** (1/3).