Math.sqrt()

Math.sqrt(x)
Returns: Number · Updated March 13, 2026 · Math
javascript math sqrt square-root

The Math.sqrt() function returns the square root of a number. For negative inputs it returns NaN, and Math.sqrt(0) returns 0.

Syntax

Math.sqrt(x)

Parameters

ParameterTypeDefaultDescription
xNumberrequiredA 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

Negative input returns NaN

Math.sqrt(-1);
// NaN

Math.sqrt(-Infinity);
// NaN

Special values

Math.sqrt(Infinity);
// Infinity

Math.sqrt(NaN);
// NaN

Pythagorean theorem

function hypotenuse(a, b) {
  return Math.sqrt(a ** 2 + b ** 2);
}

console.log(hypotenuse(3, 4));
// 5

console.log(hypotenuse(5, 12));
// 13

Common Patterns

Distance between two points

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)

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

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]

See Also

  • Math.pow() — raises a number to a given power
  • Math.exp() — returns e raised to a given power
  • [Math.abs()](/reference/math-abs/ — returns the absolute value of a number