The atan2() method divides its two arguments and computes the arctan (inverse of tangent) of the result.
Example
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 parameteryy- number that divides the parameterx
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
xandy
Note: The returned angle will always be in the range -π to π for numeric arguments.
Example 1: JavaScript Math.atan2()
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
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
The code above shows the use of the atan2() method with string arguments. That's why we get NaN as output.
Recommended readings: