Math.sqrt()
ES1+Returns the square root of a number.
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() for geometric calculations, Pythagorean theorem, standard deviation, or any formula requiring square roots.
⚠️ Common Mistakes
Not checking for negative numbers which return NaN - validate input first.
Using Math.sqrt() for nth roots when Math.pow(x, 1/n) is needed.
✅ Best Practices
For the Pythagorean theorem, use Math.hypot(a, b) instead of Math.sqrt(a*a + b*b) for better precision.
Validate that input is non-negative: const result = x >= 0 ? Math.sqrt(x) : NaN.
⚡ Performance Notes
Math.sqrt() is a native CPU operation and extremely fast. Math.hypot() is slightly slower but more numerically stable for distance calculations.
🌍 Real World Example
Distance Calculator Between Points
Calculate the Euclidean distance between two points in a 2D coordinate system.
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' }