Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Math.atan2: angle from two components

Math.atan2 returns the directed angle of point (x, y) from the positive x-axis in radians while retaining quadrant information.

Version: ECMAScript 1 onward; example target: Node.js 24.22.2

Syntax

Math.atan2(y, x)

Math.atan2(y, x) converts y first and then x with ToNumber and returns an angle in [-π, π]. The vertical component comes before the horizontal component. The signs of both numbers select the correct quadrant, so results distinguish points having the same quotient y / x.

A NaN argument yields NaN. Signed zeros select the branch boundary: atan2(+0, -1) is +π, atan2(-0, -1) is -π, and atan2(-0, +1) is -0. The specification also defines every combination involving ±Infinity. A Symbol or BigInt throws TypeError; objects can run conversion code, and approximation may be implementation-dependent.

The function is not a constructor and has been standard since ECMAScript 1. Use it for vector direction, pointer rotation, or bearings because it handles zero x and quadrants better than Math.atan(y / x). The result is in radians; degrees are angle * 180 / Math.PI. At point (0, 0), zero signs determine the result, so do not automatically treat it as a geometrically defined direction.

Examples

const points = [[1, 1], [-1, 1], [-1, -1], [1, -1]];
console.log(points.map(([x, y]) => (Math.atan2(y, x) * 180 / Math.PI).toFixed(0)).join(","));
console.log(Math.atan2(+0, -1).toFixed(6), Math.atan2(-0, -1).toFixed(6));
console.log(Object.is(Math.atan2(-0, +1), -0));
console.log(Number.isNaN(Math.atan2(undefined, 1)));
try { Math.atan2(1n, 1); } catch (error) { console.log(error instanceof TypeError); }

Result

45,135,-135,-45
3.141593 -3.141593
true
true
true

Sources