totn JavaScript

JavaScript: Math atan2() function

This JavaScript tutorial explains how to use the math function called atan2() with syntax and examples.

Description

In JavaScript, atan2() is a function that is used to return the arc tangent (in radians) of (x,y) coordinates. Because the atan2() 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 atan2() function is:

Math.atan2(y,x);

Parameters or Arguments

y
The y-coordinate of a point.
x
The x-coordinate of a point.

Returns

The atan2() function returns the arc tangent of (x,y) coordinates and the result is expressed in radians.

Note

  • Math is a placeholder object that contains mathematical functions and constants of which atan2() is one of these functions.

Example

Let's take a look at an example of how to use the atan2() function in JavaScript.

For example:

console.log(Math.atan2(8,1));
console.log(Math.atan2(0,-9));

In this example, we have invoked the atan2() function using the Math class.

We have written the output of the atan2() function to the web browser console log, for demonstration purposes, to show what the atan2() function returns.

The following will be output to the web browser console log:

1.446441332248135
3.141592653589793

In this example, the first output to the console log returned 1.446441332248135 which is the arc tangent of the (x,y) coordinate where 8 is the y-coordinate and 1 is the x-coordinate.

The second output to the console log returned 3.141592653589793 which is the arc tangent of the (x,y) coordinate where 0 is the y-coordinate and -9 is the x-coordinate.

The result from the atan2() function is expressed in radians.