Selected Reading

JavaScript Math.atan2() Method



The Math.atan2() method in JavaScript is used to calculate the arctangent of the quotient of its arguments, representing the angle in radians. It takes two parameters, y and x, and calculates the angle between the positive x-axis and the point (x, y). The result will be in the range of π to π, or -180 degrees to 180 degrees.

Syntax

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

Math.atan2(y, x)

Parameters

This method accepts only two parameters. The same are described below −

  • y: The vertical coordinate.
  • x: The horizontal coordinate.

Return value

This method returns a numeric value representing the angle in radians (between -π and π, inclusive) between the positive x-axis and the point (x, y).

Example 1

In the following example, we are using the JavaScript Math.atan2() method to calculate the arctangent of (1/1) −

<html>
<body>
<script>
   const result = Math.atan2(4, 1);
   document.write(result);
</script>
</body>
</html>

Output

If we execute the above progran, it returns approximately "0.7853" (45 degrees in radians).

Example 2

In this example, since the y parameter is 0, the resulting angle will be 0 −

<html>
<body>
<script>
   const result = Math.atan2(0, 1);
   document.write(result);
</script>
</body>
</html>

Output

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

Example 3

If we use atan2() method with Infinity, the result will still be in between -π and π −

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

Output

As we can see in the output, it returned result is in between -π and π.

Example 4

If we pass string arguments to atan2() method, the result will be "NaN" −

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

Output

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

Advertisements