How to Use Math.sqrt in JavaScript: Simple Square Root Calculation
Use
Math.sqrt(x) in JavaScript to find the square root of a number x. It returns the positive square root or NaN if x is negative.Syntax
The Math.sqrt() function takes one argument, a number, and returns its square root. If the number is negative, it returns NaN (Not a Number).
- Math.sqrt(x):
xis the number you want the square root of.
javascript
Math.sqrt(x)Example
This example shows how to calculate the square root of 16 and 25 using Math.sqrt(). It also shows what happens if you try to find the square root of a negative number.
javascript
console.log(Math.sqrt(16)); // 4 console.log(Math.sqrt(25)); // 5 console.log(Math.sqrt(-9)); // NaN
Output
4
5
NaN
Common Pitfalls
Common mistakes include passing negative numbers, which results in NaN, and passing non-numeric values, which can cause unexpected results.
Always ensure the input is a non-negative number to get a valid square root.
javascript
console.log(Math.sqrt(-4)); // NaN (wrong if expecting a real number) // Correct approach: check before calling const num = -4; if (num >= 0) { console.log(Math.sqrt(num)); } else { console.log('Cannot calculate square root of negative number'); }
Output
NaN
Cannot calculate square root of negative number
Quick Reference
| Usage | Description |
|---|---|
| Math.sqrt(x) | Returns the square root of x |
| x >= 0 | Input must be zero or positive for a real result |
| Negative input | Returns NaN (Not a Number) |
| Non-numeric input | Returns NaN or converts if possible |
Key Takeaways
Use Math.sqrt(x) to get the square root of a non-negative number x.
Passing a negative number to Math.sqrt returns NaN, not a real number.
Always check that the input is zero or positive before using Math.sqrt.
Math.sqrt only accepts one argument, the number to find the root of.
Non-numeric inputs may cause unexpected results or NaN.