Math.sqrt()
ES1+Returns the square root of a number. Negative inputs return NaN (JavaScript has no built-in complex numbers), Math.sqrt(-0) is -0, and Math.sqrt(Infinity) is Infinity. The result is the correctly rounded double nearest the true root, as IEEE 754 requires of this operation.
Syntax
Math.sqrt(x)Parameters
x number A number
Return Value
The square root of the given number, or NaN if negative
Examples
console.log(Math.sqrt(9));
console.log(Math.sqrt(2));
console.log(Math.sqrt(-1)); 📌 When to Use
Use Math.sqrt() wherever quadratic quantities return to linear scale: Euclidean distance from squared components, standard deviation from variance, RMS values in signal processing, solving quadratics via the discriminant, circle radii from areas, and normalizing vectors in graphics and physics. It is a workhorse of geometry code: collision detection, camera distance, gradient magnitudes, and layout math that involves diagonals all funnel through it. Two practical refinements matter often. For 2D/3D distance, Math.hypot(dx, dy) computes sqrt(dx² + dy²) with protection against intermediate overflow and underflow, when dx is around 1e200, dx * dx overflows to Infinity even though the true distance is representable, so hypot is the robust choice at extreme magnitudes (plain sqrt of the sum is fine, and faster, for ordinary coordinates). And for comparisons, you frequently do not need the root at all: checking whether a distance is under a threshold works on squared values (dx*dx + dy*dy < r*r), saving the sqrt entirely, a standard optimization in collision loops. Validate domain at boundaries: data that can go negative through float error (a variance computed as mean-of-squares minus square-of-mean can be -1e-16) should be clamped to zero before the root, or you will emit NaN from mathematically valid statistics.
⚠️ Common Mistakes
Feeding it negatives and not noticing: Math.sqrt(-4) is NaN, silently. The insidious version is a value that is negative only by floating-point error, variance formulas and discriminants produce -1e-17 where mathematics says 0, so robust code clamps with Math.max(0, v) before rooting.
Reconstructing hypot naively at extreme scales: Math.sqrt(a*a + b*b) overflows to Infinity when a exceeds about 1e154 (since a² overflows the double range), and underflows to 0 for tiny components; Math.hypot(a, b) is engineered for exactly these regimes.
Testing perfect squares with Number.isInteger(Math.sqrt(n)): reliable for n within safe-integer range, but beyond 2^53 the input itself cannot represent every integer, so both false positives and negatives occur; large-integer perfect-square checks belong in BigInt logic.
Taking sqrt inside comparison loops: computing the root of every distance just to compare against a radius does an expensive-ish operation n times for no informational gain; compare squared distances against the squared threshold instead.
Assuming sqrt fixes upstream precision: Math.sqrt correctly rounds its input's root, but if the input was already polluted (0.1 + 0.2 arithmetic), the root faithfully reflects the polluted value; precision problems must be addressed where they arise.
Using Math.pow(x, 0.5) out of habit: it is specified to give the same results as Math.sqrt for normal inputs but reads worse, may be marginally slower, and loses the intent signal that dedicated functions carry (there are also edge-case differences: Math.pow(-0, 0.5) is +0 while Math.sqrt(-0) is -0).
✅ Best Practices
Reach for Math.hypot for distances and magnitudes: Math.hypot(dx, dy) (and its 3-argument form) states the formula, resists overflow, and handles the signs for you; reserve manual sqrt-of-sum for hot loops with known-ordinary magnitudes.
Compare in squared space when only ordering matters: precompute r2 = r * r and test dx*dx + dy*dy <= r2; document the convention so later readers do not "fix" the missing sqrt.
Clamp float-noise negatives at domain boundaries: const sd = Math.sqrt(Math.max(0, variance)); pair it with Number.isFinite input validation so statistics code degrades predictably on dirty data.
Normalize vectors defensively: length can be 0, and dividing by Math.sqrt(0) yields Infinity/NaN components; guard zero-length before dividing (if (len > 0) { x /= len; y /= len; }).
Keep numerically sensitive formulas in their stable forms: for quadratics, the textbook (-b ± √disc) / 2a form loses digits when b² dominates 4ac; the stable variant multiplies by the conjugate, worth using in scientific-grade code.
⚡ Performance Notes
Math.sqrt() compiles to the hardware square-root instruction on every modern platform, costing a handful of cycles, more than a multiply, far less than a transcendental like sin or pow with fractional exponents, and it is inlined by JITs, so calling it per entity per frame is routine in games. Math.hypot is noticeably slower (several times, engine-dependent) because of its overflow-safe algorithm, which is why the squared-comparison trick and plain sqrt remain standard in collision hot paths while hypot serves general-purpose code. There is no worthwhile fast-inverse-sqrt-style hack in JavaScript: engines and hardware already beat the classic bit tricks, and typed-array code with plain Math.sqrt vectorizes reasonably in WebAssembly-adjacent workloads. As usual, memory layout dominates: structure-of-arrays with Float64Array/Float32Array around the sqrt matters more than the sqrt itself.
🌍 Real World Example
Distance Calculator Between Points
Distance between points is the geometry primitive everything else borrows: this example applies the Pythagorean theorem to coordinate deltas to answer "how far apart", the calculation behind map radius filters ("stores within 5 km" after projecting), collision detection, snap-to-grid thresholds in editors, and gesture-distance detection on touch screens. It also demonstrates where Math.hypot slots in as the robust variant, and why real collision systems often keep the comparison in squared space, computing the root only for the distances a user will actually see.
function calculateDistance(point1, point2) {
const dx = point2.x - point1.x;
const dy = point2.y - point1.y;
// Traditional way
const distance = Math.sqrt(dx * dx + dy * dy);
// Modern alternative (better precision for extreme values)
const preciseDistance = Math.hypot(dx, dy);
return {
distance: distance.toFixed(2),
preciseDistance: preciseDistance.toFixed(2)
};
}
const pointA = { x: 0, y: 0 };
const pointB = { x: 3, y: 4 };
console.log(calculateDistance(pointA, pointB));
// { distance: '5.00', preciseDistance: '5.00' }