JavaScript Math.hypot(): Hypotenuse and Distance Examples

Deepak Prasad

JavaScript Math.hypot() returns the square root of the sum of squares of its arguments. It is commonly used for hypotenuse length, vector magnitude, and distance between points.

Environment: Node.js v20.18.2. Each snippet is plain JavaScript; the line after it states the expected console output.


Math.hypot Syntax

Right triangle illustrating Math.hypot as length of hypotenuse from legs x and y

javascript
Math.hypot(value1, value2, ...valueN)
Output

It returns sqrt(value1² + value2² + ... valueN²).


Method 1: Calculate a 3-4-5 Hypotenuse

javascript
console.log(Math.hypot(3, 4));
Output

You should see one line logging 5.


Method 2: Calculate 3D Vector Length

javascript
console.log(Math.hypot(2, 3, 6));
Output

You should see one line logging 7.


Method 3: Calculate Distance Between Two Points

javascript
const distance = Math.hypot(4 - 1, 6 - 2);

console.log(distance);
Output

You should see one line logging 5.


Method 4: Call Math.hypot with No Arguments

javascript
console.log(Math.hypot());
Output

You should see one line logging 0.


Common Questions About Math.hypot

What does Math.hypot do?

It returns the square root of the sum of squares of its arguments.

How do I calculate distance between points in JavaScript?

Use Math.hypot(x2 - x1, y2 - y1) for 2D points.

Can Math.hypot take more than two values?

Yes. It can calculate vector length across any number of dimensions.


Summary

Math.hypot computes √(x² + y² + …) with less overflow risk than expanding squares yourself.

JavaScript Math.hypot() is the clean built-in method for hypotenuse length, vector magnitude, and distance between points. Use Math.hypot(3, 4) for a 2D hypotenuse, Math.hypot(x2 - x1, y2 - y1) for point distance, and more arguments for higher-dimensional vectors.


Official Documentation

Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital experiences across various domains.

  • JavaScript
  • Web Design