JavaScript: Math hypot() function
This JavaScript tutorial explains how to use the math function called hypot() with syntax and examples.
Description
In JavaScript, hypot() is a function that is used to return the square root of the sum of squares of the parameters provided. Because the hypot() function is a static function of the Math object, it must be invoked through the placeholder object called Math.
Syntax
In JavaScript, the syntax for the hypot() function is:
Math.hypot([number1, number2, ... number_n]);
Parameters or Arguments
- number1, number2, ... number_n
- Optional. The numbers that will be used in the calculation.
Returns
The hypot() function returns the square root after summing the squares of the parameters provided:
√ number12 + number22 + number_n2
Note
- Math is a placeholder object that contains mathematical functions and constants of which hypot() is one of these functions.
-
You can use the hypot() function to calculate the hypotenuse of a right angled triangle where a and b are the lengths of the legs of the triangle:
hypotenuse = √ a2 + b2
Example
Let's take a look at an example of how to use the hypot() function in JavaScript.
For example:
console.log(Math.hypot(1));
console.log(Math.hypot(2, 3));
console.log(Math.hypot(8, 1, -5));
In this example, we have invoked the hypot() function using the Math class.
We have written the output of the hypot() function to the web browser console log, for demonstration purposes, to show what the hypot() function returns.
The following will be output to the web browser console log:
1 3.6055512754639896 9.486832980505138
In this example, the first output to the console log returned 1 which the result of the calculation √12
.
The second output to the console log returned 3.6055512754639896 which the result of the calculation √22 + 32
.
The third output to the console log returned 9.486832980505138 which the result of the calculation √82 + 12 + -52
.
Advertisements