JavaScript Math.hypot()

The Math.hypot() method returns the square root of the sum of squares of its arguments.

Example

// the square root of the sum of 3 and 4 var num = Math.hypot(3, 4);
console.log(num); // 5

hypot() Syntax

The syntax of the hypot() method is:

Math.hypot(n1, n2, ..., nx)

Here, hypot() is a static method. Hence, we need to access the method using the class name, Math.


hypot() Parameters

The hypot() method takes in arbitrary (one or more) numbers as arguments.

  • n1 - a number
  • n2 - a number, and so on.

hypot() Return Value

The hypot() method returns:

  • the square root of the sum of squares of the given arguments.
  • NaN if any argument is non-numeric.
  • 0 if no arguments are given.

Example 1: JavaScript Math.hypot()

// the square root of the sum of 0.7 and 2.4 var num1 = Math.hypot(0.7, 2.4);
console.log(num1); // 2.5
// the square root of the sum of 7, 24, and 25 var num2 = Math.hypot(7, 24, 25);
console.log(num2); // 35.35533905932738

In the above example,

  • Math.hypot(0.7, 2.4) computes the square root of the sum of squares of 0.7 and 2.4
  • Math.hypot(7, 24, 25) computes the square root of the sum of squares of 7, 24, and 25

Example 2: hypot() With a Single Argument

// the square root of the sum of squares of -3 var num = Math.hypot(-3);
console.log(num); // 3

In the above example, we have used Math.hypot() to compute the square root of the sum of squares of -3.

The output 3 indicates that for single-value arguments, their absolute values are returned.


Example 3: hypot() With No Arguments

// call hypot() without passing any arguments var num = Math.hypot();
console.log(num); // 0

In the above example, we have used Math.hypot() to compute the square root without passing any argument.

The output indicates that 0 is returned if we don't pass any argument.


Recommended Readings:

Did you find this article helpful?