w3resource

JavaScript : Pythagorean function in JavaScript

JavaScript Math: Exercise-19 with Solution

Pythagorean Theorem

Create a Pythagorean function in JavaScript.

Note : The Pythagorean Theorem tells us that the relationship in every right triangle is : c2 = a2 + b2, where c is the hypotenuse and a, b are two legs of the triangle.

Test Data:
console.log(pythagorean_theorem(2, 4));
console.log(pythagorean_theorem(3, 4));
Output :
4.47213595499958
5

Sample Solution:

JavaScript Code:

// Define a function named pythagorean_theorem that calculates the hypotenuse of a right triangle given the lengths of its two legs.
function pythagorean_theorem(x, y) {
    // Check if both x and y are of type number, if not, return false.
    if ((typeof x !== 'number') || (typeof y !== 'number')) 
        return false; 
    // Calculate and return the square root of the sum of the squares of x and y (hypotenuse).
    return Math.sqrt(x * x + y * y);
}

// Output the result of calculating the hypotenuse of a triangle with legs of lengths 2 and 4 to the console.
console.log(pythagorean_theorem(2, 4));
// Output the result of calculating the hypotenuse of a triangle with legs of lengths 3 and 4 to the console.
console.log(pythagorean_theorem(3, 4));

Output:

4.47213595499958
5

Flowchart:

Flowchart: JavaScript Math- Pythagorean function in JavaScript

Live Demo:

See the Pen javascript-math-exercise-19 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that calculates the hypotenuse of a right triangle using the Pythagorean theorem.
  • Write a JavaScript function that verifies if three given sides can form a right triangle based on the Pythagorean theorem.
  • Write a JavaScript function that computes the missing side of a right triangle when given the hypotenuse and one leg.
  • Write a JavaScript function that checks a set of side lengths and returns true if they satisfy the Pythagorean theorem.

Go to:


PREV : Product of Array Values.
NEXT : Binomial Coefficients.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.