Sub topic 15
Trigonometry, Radians, and Math.atan2
This chapter assumes you know the Math object basics from earlier chapters. It also assumes you know that floating-point results carry small rounding errors and that % keeps the sign of the dividend. You should remember a little school trigonometry: sine and cosine on a unit circle, and what an angle in degrees means. The focus here is how JavaScript exposes trigonometry and where code that uses it usually goes wrong.
The Working Model: Everything Is in Radians
Every trigonometric function on Math takes or returns angles in radians. One full turn is 2 * Math.PI radians, which equals 360 degrees. The Math object never uses degrees, and it never warns you when you pass it degrees by mistake.
console.log(Math.sin(90)); // 0.8939966636005579 (90 radians, not 90 degrees)
console.log(Math.sin(90 * Math.PI / 180)); // 1The first line is the most common trigonometry bug in JavaScript. It runs without error and returns a plausible number, so it can go unnoticed for a long time.
The usual fix is to convert at the boundary. Keep radians inside your calculations, and convert only where degrees come in (user input, config files, CSS) or go out (display).
const toRadians = (deg) => deg * (Math.PI / 180);
const toDegrees = (rad) => rad * (180 / Math.PI);
console.log(toRadians(180)); // 3.141592653589793
console.log(toDegrees(Math.PI / 4)); // 45The Trigonometric Functions at a Glance
| Function | Input | Output | Notes |
|---|---|---|---|
| `Math.sin(x)`, `Math.cos(x)` | radians | -1 to 1 | Defined for every finite x |
| `Math.tan(x)` | radians | any number | Huge values near odd multiples of π/2, never Infinity |
| `Math.asin(v)`, `Math.acos(v)` | -1 to 1 | radians | `NaN` outside [-1, 1] |
| `Math.atan(v)` | any number | -π/2 to π/2 | Loses quadrant information |
| `Math.atan2(y, x)` | coordinates | -π to π | Full-circle angle of the point (x, y) |
| `Math.sinh`, `cosh`, `tanh`, `asinh`, `acosh`, `atanh` | numbers | numbers | Hyperbolic variants, not angle-based |
| `Math.hypot(...v)` | numbers | number | Length of a vector, avoids overflow |
Gotcha: Exact Angles Give Inexact Results
Math.PI is the closest double to π, not π itself. Functions that should return exactly 0 at π or π/2 return tiny leftover values instead:
console.log(Math.sin(Math.PI)); // 1.2246467991473532e-16
console.log(Math.cos(Math.PI / 2)); // 6.123233995736766e-17
console.log(Math.tan(Math.PI / 2)); // 16331239353195370Math.tan(Math.PI / 2) does not return Infinity because the argument is slightly less than the true π/2. If your code checks Math.cos(angle) === 0, that check will fail. Compare against a tolerance, as you would with any float:
const isNearZero = (v, eps = 1e-12) => Math.abs(v) < eps;
console.log(isNearZero(Math.cos(Math.PI / 2))); // trueTo show such results to a person, round them for display with toFixed or Intl.NumberFormat. Do not round them in the middle of a calculation.
Gotcha: Inverse Functions Return NaN on Slightly Bad Input
Math.acos and Math.asin accept only values from -1 to 1. A common route to NaN is computing the angle between two vectors with the dot-product formula. Rounding error can push the ratio to 1.0000000000000002:
function angleBetween(ax, ay, bx, by) {
const dot = ax * bx + ay * by;
const lengths = Math.hypot(ax, ay) * Math.hypot(bx, by);
const ratio = Math.min(1, Math.max(-1, dot / lengths)); // clamp into [-1, 1]
return Math.acos(ratio);
}
console.log(angleBetween(1, 0, 0, 1) * 180 / Math.PI); // 90
console.log(angleBetween(3, 3, 1, 1)); // 0 (not NaN)Without the clamp, parallel vectors can produce NaN. That NaN then spreads silently through every later calculation.
Why Math.atan2 Beats Math.atan
To find the angle of a point (x, y) from the origin, the textbook answer is atan(y / x). In code this answer breaks in two ways:
- The division throws away the signs. Points (1, 1) and (-1, -1) both give
y / x === 1, so they get the same angle even though they point in opposite directions. - When
xis 0,y / xisInfinityorNaN.
Math.atan2(y, x) takes the two coordinates separately. It uses both signs to pick the correct quadrant, and it returns an angle from -π to π. The argument order is y first, then x. Swapping them is the second most common bug in this chapter.
const deg = (rad) => rad * 180 / Math.PI;
console.log(deg(Math.atan(-1 / -1))); // 45 (wrong for the point (-1, -1))
console.log(deg(Math.atan2(-1, -1))); // -135 (correct)
console.log(deg(Math.atan2(1, 0))); // 90 (no division by zero)
console.log(deg(Math.atan2(0, -1))); // 180
console.log(deg(Math.atan2(-0, -1))); // -180
console.log(Math.atan2(0, 0)); // 0The two lines with 0 and -0 give different answers. atan2 is one of the few functions where negative zero changes the result. An angle on the negative x-axis can come out as 180 or -180 depending on how the zero was produced. If your code depends on that boundary, normalize the angle.
Normalizing and Comparing Angles
atan2 returns angles from -180° to 180°, but many interfaces expect 0° to 360°. % keeps the sign of the dividend, so you need the same adjustment you use for a true modulo:
const normalize360 = (d) => ((d % 360) + 360) % 360;
console.log(normalize360(-135)); // 225
console.log(normalize360(720)); // 0
console.log(normalize360(370)); // 10Subtracting two headings has a related trap. The difference between 350° and 10° is 20°, not 340°. This function returns the signed shortest turn from a to b:
function shortestTurn(a, b) {
return ((((b - a) % 360) + 540) % 360) - 180;
}
console.log(shortestTurn(350, 10)); // 20
console.log(shortestTurn(10, 350)); // -20
console.log(shortestTurn(0, 180)); // -180Practical Patterns
Moving at an angle
Games and animations often convert a heading and speed into x and y steps. Cosine gives the x component and sine gives the y component:
function step(x, y, headingDeg, speed) {
const r = headingDeg * Math.PI / 180;
return { x: x + Math.cos(r) * speed, y: y + Math.sin(r) * speed };
}
console.log(step(0, 0, 0, 10)); // { x: 10, y: 0 }
console.log(step(0, 0, 90, 10)); // { x: 6.123233995736766e-16, y: 10 }Rotating a point around the origin
function rotate(x, y, rad) {
const c = Math.cos(rad);
const s = Math.sin(rad);
return { x: x * c - y * s, y: x * s + y * c };
}
console.log(rotate(1, 0, Math.PI / 2)); // { x: 6.123233995736766e-17, y: 1 }If you rotate an object repeatedly, rounding error adds up a little on every call. Store the total angle and rotate the original point once. Do not apply many small rotations one after another.
Distance and direction between two points
function polar(fromX, fromY, toX, toY) {
const dx = toX - fromX;
const dy = toY - fromY;
return { distance: Math.hypot(dx, dy), angle: Math.atan2(dy, dx) };
}
const p = polar(0, 0, 3, 4);
console.log(p.distance); // 5
console.log(p.angle * 180 / Math.PI); // 53.13010235415598Decision Summary
- Use
Math.atan2(dy, dx)for the direction of any vector. UseMath.atanonly when you truly have a single ratio. - Convert degrees to radians once, at the input boundary.
- Clamp before calling
acosorasin. - Compare trigonometric results with a tolerance, and round only for display.
- Normalize angles before you compare or display them.
Exercise
A pointer at screen position (100, 100) should face the mouse at (40, 160). Write the expression for the angle in degrees, normalized to [0, 360). What value does it give, and why would Math.atan(dy / dx) give the wrong answer here?
Show answer
dx = -60 and dy = 60, so use ((Math.atan2(60, -60) * 180 / Math.PI) % 360 + 360) % 360, which gives 135. Math.atan(60 / -60) is Math.atan(-1), which gives -45 degrees. The division drops the signs of dx and dy, so atan cannot tell this point apart from (160, 40) and puts the angle in the wrong quadrant. Because screen y points down, 135 here means down and to the left.
Exercise
A function returns Math.acos(dot / (lenA * lenB)) and sometimes returns NaN for two vectors that point the same way. Explain the cause and give the fix.
Show answer
Rounding error can make the ratio slightly greater than 1, for example 1.0000000000000002. Math.acos is only defined on [-1, 1], so it returns NaN. Clamp the ratio first: Math.acos(Math.min(1, Math.max(-1, ratio))).
Exercise
Why does Math.cos(Math.PI / 2) === 0 evaluate to false, and what should you write instead?
Show answer
Math.PI is only the closest double to π, so Math.PI / 2 is slightly off from the true π/2. Its cosine is about 6.12e-17, not 0. Use a tolerance check such as Math.abs(Math.cos(Math.PI / 2)) < 1e-12.