Calculate the hypotenuse of a right triangle in JavaScript

We are required to write a JavaScript function that takes in two numbers. The first number represents the length of the base of a right triangle and the second is perpendicular. The function should then compute the length of the hypotenuse based on these values.

For example ?

If base = 8, perpendicular = 6

Then the output should be 10

The Pythagorean Theorem

The hypotenuse is calculated using the Pythagorean theorem: c² = a² + b², where c is the hypotenuse and a, b are the other two sides.

base (a) perpendicular (b) hypotenuse (c) c² = a² + b²

Example

Following is the code ?

const base = 8;
const perpendicular = 6;
const findHypotenuse = (base, perpendicular) => {
   const bSquare = base ** 2;
   const pSquare = perpendicular ** 2;
   const sum = bSquare + pSquare;
   const hypotenuse = Math.sqrt(sum);
   return hypotenuse;
};
console.log(findHypotenuse(base, perpendicular));
console.log(findHypotenuse(34, 56));

Output

Following is the output on console ?

10
65.5133574166368

Using Math.hypot() Method

JavaScript provides a built-in Math.hypot() method that directly calculates the hypotenuse:

const findHypotenuseBuiltIn = (base, perpendicular) => {
   return Math.hypot(base, perpendicular);
};

console.log(findHypotenuseBuiltIn(8, 6));
console.log(findHypotenuseBuiltIn(34, 56));
console.log(findHypotenuseBuiltIn(3, 4));
10
65.5133574166368
5

Comparison

Method Code Length Performance Readability
Manual Calculation Longer Good Shows the math
Math.hypot() Shorter Optimized Clean and direct

Conclusion

Both methods work effectively for calculating the hypotenuse. Use Math.hypot() for cleaner code, or the manual approach when you need to show the mathematical steps explicitly.

Updated on: 2026-03-15T23:19:00+05:30

791 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements