JavaScriptNumbers and Math
Math. sqrt()
Returns the square root of a number.
- Returns
- The square root, or
NaNfor negative numbers.
Example
#JavaScript
console.log(Math.sqrt(144))
console.log(Math.sqrt(2))
console.log(Math.sqrt(-1))
const distance = (a, b) => Math.sqrt((b.x - a.x) ** 2 + (b.y - a.y) ** 2)
console.log(distance({ x: 0, y: 0 }, { x: 3, y: 4 }))Console
12
1.4142135623730951
NaN
5
Definition and usage
#The Math.sqrt() function returns the square root of a number, that is, the value which, multiplied by itself, gives the number back. For negative numbers it returns NaN.
It shows up most often in geometry and games: in the Pythagorean theorem, when calculating the distance between two points on the screen.
For a cube root, use Math.cbrt(), and for any other root, the exponentiation operator with a fraction, e.g. x ** (1 / 4).
Syntax
#Syntax
Math.sqrt(x)Parameters
#x
number
A non-negative number.
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- For the distance between points, the
Math.hypot(dx, dy)function is also handy. - If you’re only comparing which distance is larger, you can skip the square root and compare the squares instead.
Related entries
#Spotted a mistake or missing an example? Write to us.