JavaScript Reference ยท Math
Math.hypot()
Reference for Math.hypot(): the square root of the sum of squares, for distances, vector lengths and hypotenuses, with overflow-safe behavior explained.
Math.hypot() returns the square root of the sum of the squares of its arguments: Math.hypot(3, 4) is 5. With two arguments that is the length of the hypotenuse of a right triangle; with more it is the length of a vector in any number of dimensions.
You could write Math.sqrt(a * a + b * b) yourself, but hypot() is shorter, accepts any number of values, and avoids false overflow or underflow when the squares of very large or very small numbers leave the range of a double.
Math.hypot(value1, value2, /* โฆ, */ valueN)
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
Math.hypot() Math.hypot(value1) Math.hypot(value1, value2, /* โฆ, */ valueN)
| Name | Description |
|---|---|
value1, โฆ, valueN |
The components. Each is converted to a number. |
Return value: the square root of the sum of the squares of the arguments. It is 0 when there are no arguments, Infinity if any argument is Infinity or -Infinity, otherwise NaN if any argument is NaN or cannot be converted.
Exceptions: a BigInt argument throws a TypeError.
Usage notes
- Overflow-safe. Engines scale the values internally, so large inputs that would overflow when squared still give a finite result when the true answer fits.
- Any dimension. Pass two numbers for 2D, three for 3D. To measure an array, spread it:
Math.hypot(...components). - Single argument returns its absolute value.
- Accuracy. The result is an approximation, like any root; the exact rounding of the last digit can differ between engines, so compare with a tolerance.
- Speed.
hypot()can be slower than a hand-writtenMath.sqrt(x * x + y * y). In hot loops, such as particle simulations, compare squared distances to avoid the root, or use the manual form when the numbers are small and safe. InfinitybeatsNaN:Math.hypot(NaN, Infinity)isInfinitybecause the length is infinite whatever the other component is.- Function length is
2, a historical quirk that does not limit the number of arguments.
Browser support
Part of ES2015 and supported in all current browsers.