JavaScript Math atan2()

In this tutorial, you will learn about the JavaScript Math.atan2() method with the help of examples.

The atan2() method divides its two arguments and computes the arctan (inverse of tangent) of the result.

Example

let num = Math.atan2(4, 3);
console.log(num); 

// Output: 0.9272952180016122

atan2() Syntax

The syntax of the atan2() method is:

Math.atan2(x, y)

Here, tan() is a static method. Hence, we are accessing the method using the class name, Math.


atan2() Parameters

The atan2() method takes two parameters:

  • x - number, which is divided by the parameter y
  • y - number that divides the parameter x

Here, the method computes the arctangent of x / y.


atan2() Return Value

The method returns:

  • angle (in radians) after computing the arctan of x / y
  • NaN (Not a Number) for non-numeric arguments x and y

Note: The returned angle will always be in the range to π for numeric arguments.


Example 1: JavaScript Math.atan2()

// compute the arctangent of 5 / 2 let result1 = Math.atan2(5, 2);
console.log(result1);
// compute the arctangent of 0 / 5 let result2 = Math.atan(0, 5);
console.log(result2); // Output: // 1.1902899496825317 // 0

In the above example,

  • Math.atan2(5, 2) - computes the arctan of 2.5 ( 5 / 2 )
  • Math.atan2(0, 5) - computes the arctan of 0 ( 0 / 5 )

Example 2: Math.atan2() with Infinity

// atan2() with positive infinity
let num = Math.atan2(Infinity, 0);
console.log(num);   

// atan2() with negative infinity 
let num = Math.atan2(-Infinity, 0);
console.log(num);    

// atan2() with both infinities
let num = Math.atan2(Infinity, -Infinity);
console.log(num); 

// Output:
// 1.5707963267948966 (π/2)
// -1.5707963267948966 (-π/2)
// 2.356194490192345 (3*π/4)

Here, you can see we have successfully used the atan2() method with infinity. And the result is still between and π even though we have used it with infinity.


Example 3: Math.atan2() with Non-Numeric Arguments

// string variables
let str1 = "John";
let str2 = "Wick";

// atan2() with string arguments let result = Math.atan2(str1, str2);
console.log(result); // Output: NaN

The code above shows the use of the atan2() method with string arguments. That's why we get NaN as output.


Recommended readings:

Did you find this article helpful?