Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Math

Math.sqrt()

Reference for Math.sqrt(): computing square roots, handling negative numbers and NaN, perfect-square checks, distances and precision limits.

Math.sqrt() returns the square root of a number: the value that, multiplied by itself, gives the argument. Math.sqrt(9) is 3 and Math.sqrt(2) is about 1.414.

The argument is converted to a number first. For negative numbers there is no real square root, so the result is NaN; JavaScript has no built-in complex numbers.

JavaScript
Math.sqrt(x)

Try it

JS Square roots

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Perfect squares and distance

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
Math.sqrt(x)
Name Description
x A number (or a value that converts to one).

Return value: the non-negative square root of x. The result is NaN if x is negative (except -0) or not a number. Math.sqrt(-0) is -0, and Math.sqrt(Infinity) is Infinity.

Exceptions: a BigInt argument throws a TypeError.

Usage notes

  • Negative input gives NaN, not an error. Validate input when a negative value would be a bug.
  • Precision. Math.sqrt() is correctly rounded for the double result in practice, but the result of an irrational root can never be exact. Do not compare roots with === after more arithmetic; use a tolerance such as Number.EPSILON.
  • Perfect-square test. Taking the root and checking Number.isInteger() works well for numbers well below 2^53. For huge integers, use BigInt with an integer root algorithm.
  • ** alternative. x ** 0.5 computes the same value for most inputs, but Math.sqrt() is more readable and keeps -0 as -0.
  • Distances. For two or three components, Math.hypot() avoids overflow and underflow in intermediate squares.
  • Performance. It maps to a hardware instruction in most engines; comparing squared distances avoids the call when you only need to know which of two values is bigger.
  • Cube and other roots: use Math.cbrt() or x ** (1 / n).

Browser support

Supported in every browser and in Node.js.