How to get the square root of a number in JavaScript
Calculating square roots is important for geometric calculations, distance formulas, statistical analysis, and implementing features like Pythagorean theorem calculations or scientific computations in JavaScript applications.
With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented square root calculations in components like geometric utilities, mathematical tools, and data visualization features where precise mathematical operations are essential for accurate results.
From my extensive expertise, the most reliable and mathematically accurate approach is using the built-in Math.sqrt()
function.
This method provides optimized square root calculation with proper handling of edge cases and floating-point precision.
Use Math.sqrt()
to calculate the square root of a number.
const number = 16
const squareRoot = Math.sqrt(number)
// Result: 4
const decimal = 2.25
const decimalRoot = Math.sqrt(decimal)
// Result: 1.5
The Math.sqrt()
function returns the square root of a number, which is the value that when multiplied by itself equals the original number. In these examples, Math.sqrt(16)
returns 4
because 4 × 4 = 16, and Math.sqrt(2.25)
returns 1.5
because 1.5 × 1.5 = 2.25. The function handles both integers and decimal numbers accurately. For negative numbers, it returns NaN
since square roots of negative numbers are not real numbers in standard mathematics. Math.sqrt(0)
returns 0
.
Best Practice Note:
This is the same approach we use in CoreUI components for geometric calculations, distance measurements, and mathematical utilities across our component library.
Always validate input for negative values if your application requires real number results. For complex numbers or negative inputs, consider using specialized math libraries. The Math.sqrt()
function provides IEEE 754 compliant results and is optimized for performance in all JavaScript environments.