Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Math.cos: cosine

Math.cos converts an angle in radians to Number and returns an approximate cosine in the range -1 through 1.

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

Syntax

Math.cos(x)

Math.cos(x) applies ToNumber and computes the cosine of angle x expressed in radians. For either zero, the result is exactly 1. For finite arguments the mathematical result lies in [-1, 1], but it is represented as a Number; for example, cosine of π/2 can be a tiny value instead of exact zero.

NaN, +Infinity, -Infinity, or a missing argument yields NaN. A numeric string is converted, while a Symbol or BigInt throws TypeError; an object can invoke valueOf or toString. Accuracy of the approximation and argument reduction for very large angles may be implementation-dependent.

The function is not a constructor and has been standard since ECMAScript 1. Convert degrees with degrees * Math.PI / 180. Cosine supplies the horizontal circle component and appears in rotation as xPrime = x * cos(a) - y * sin(a). Compare trigonometric results with a tolerance rather than strict equality.

Examples

function rotate([x, y], degrees) {
  const angle = degrees * Math.PI / 180;
  return [x * Math.cos(angle) - y * Math.sin(angle), x * Math.sin(angle) + y * Math.cos(angle)];
}
const [x, y] = rotate([2, 0], 90);
console.log(x.toFixed(3), y.toFixed(3));
console.log(Math.cos(0), Math.cos(Math.PI).toFixed(1));
console.log(Number.isNaN(Math.cos(Infinity)), Number.isNaN(Math.cos()));
try { Math.cos(1n); } catch (error) { console.log(error instanceof TypeError); }

Result

0.000 2.000
1 -1.0
true true
true

Sources