Math.atan2 for Two-Argument Arctangent
You'll learn how to use Math.atan2() to calculate angles from coordinates with automatic quadrant handling.
The Problem with Regular Arctangent
When you learned about Math.atan(), you discovered it could calculate angles from ratios. But there's a catch: Math.atan(y/x) loses information about which quadrant your point is in. For example, both (1,1) and (-1,-1) give the same ratio, but they're in opposite quadrants!
Why Math.atan2 is Superior
Math.atan2(y, x) takes two separate arguments — the y-coordinate first, then the x-coordinate. This lets JavaScript determine the correct quadrant automatically and return an angle between -π and π radians (or -180° to 180°).
Think of it like giving directions: instead of just saying "go 45 degrees," you're saying "go northeast" (positive x and y) versus "go southwest" (negative x and y) — the destination matters!
Practical Usage
// Point in first quadrant (northeast)
Math.atan2(1, 1); // ≈ 0.785 (45°)
// Point in third quadrant (southwest) - different result!
Math.atan2(-1, -1); // ≈ -2.356 (-135° or 225°)
// Directly pointing right
Math.atan2(0, 5); // 0 (0°)
// Directly pointing up
Math.atan2(5, 0); // ≈ 1.571 (90°)
// Calculate angle from origin to a point
const x = 3, y = 4;
const angleInRadians = Math.atan2(y, x);
const angleInDegrees = angleInRadians * (180 / Math.PI);
console.log(angleInDegrees); // ≈ 53.13°
Note: The order is Math.atan2(y, x) — y comes first! This trips up many developers.
Key Takeaway: Use Math.atan2(y, x) instead of Math.atan(y/x) when working with coordinates to get the correct angle in all four quadrants, returned as a value between -π and π radians.