basic
Math.sqrt
Returns the positive square root of a number. Equivalent to Math.pow(x, 0.5) but faster and clearer.
Math.sqrt(x) Parameters & edge cases
| Case | Behavior |
|---|---|
| x | The number to take the root of; must be >= 0 for a real result |
| negative input | Math.sqrt(-1) returns NaN — JavaScript has no complex numbers |
| Infinity | Math.sqrt(Infinity) returns Infinity |
Examples
console.log(Math.sqrt(16)); // 4 Perfect square.
console.log(Math.sqrt(2)); // 1.4142135623730951 Irrational — the classic √2 constant.
console.log(Math.sqrt(-1)); // NaN Negative inputs return NaN, not -1 or an imaginary.
console.log(Math.sqrt(0)); // 0 sqrt(0) is exactly 0.
Gotcha
For distance calculations of multiple components, prefer Math.hypot(...) — it avoids intermediate overflow/underflow that Math.sqrt(a*a + b*b) can suffer.
Related
Math.cbrt
Returns the cube root of a number. Introduced in ES2015, and unlike sqrt it handles negative inputs correctly.
Math.hypot
Returns the square root of the sum of squares of its arguments — the Euclidean norm. Introduced in ES2015 and safer than manual sqrt(a*a + b*b) against overflow.
Math.pow
Returns base raised to the power of exponent. In modern code the `**` operator (ES2016) is usually preferred for readability and identical semantics.
Math.abs
Returns the absolute value of a number — its distance from zero without regard to sign. Useful for differences, magnitudes, and tolerance checks.