JavaScript Math.hypot() Method



The Math.hypot() method in JavaScript accepts one or more numbers as arguments and calculates the square root of the sum of squares for its arguments. It is commonly used to find the Euclidean distance between two points in a coordinate system.

This method returns "Infinity", if any of the arguments is Infinity. If at least one of the argument is NaN, returns NaN. It returns 0, if no arguments are provided or all arguments are 0.

Syntax

Following is the syntax of JavaScript Math.hypot() method −

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

Parameters

This method accepts one or more numbers as arguments.

  • value1: A numeric value.
  • value2: A numeric value, and so on.

Return value

This method returns square root of the sum of squares of the provided arguments.

Example 1

In the example, the Math.hypot(5, 12) calculates the hypotenuse of a right-angled triangle with sides of length 5 and 12.

<html>
<body>
<script>
   const result = Math.hypot(5, 12);
   document.write(result);
</script>
</body>
</html>

Output

If we execute the above program, the value of hypotenuse will be 13.

Example 2

Here, the Math.hypot(1, 2, 3) calculates the Euclidean distance in a 3-D space. It finds the square root of the sum of the squares of the three values (1, 2, 3) −

<html>
<body>
<script>
   const result = Math.hypot(1, 2, 3);
   document.write(result);
</script>
</body>
</html>

Output

If we execute the above program, it returns approximately 3.74.

Example 3

If we provide string values as arguments, this method returns NaN as result −

<html>
<body>
<script>
   const result = Math.hypot("Tutotrialspoint", "Tutorix");
   document.write(result);
</script>
</body>
</html>

Output

As we can see in the output, it returned NaN as result.

Example 4

If we provide Infinity as arguments, this method returns Infinity as result −

<html>
<body>
<script>
   const result = Math.hypot(Infinity);
   document.write(result);
</script>
</body>
</html>

Output

As we can see in the output, it returned Infinity as result.

Example 5

If no arguments are provided or all arguments are 0, this method returns 0 as result −

<html>
<body>
<script>
   const result1 = Math.hypot();
   const result2 = Math.hypot(0);
   document.write(result1, "<br>", result2);
</script>
</body>
</html>

Output

As we can see in the output, it returned 0 as result for both cases.

Advertisements