Math.cos()
ES1+Returns the cosine of a number (in radians).
Syntax
Math.cos(x)Parameters
x number A number in radians
Return Value
The cosine of the given number
Examples
console.log(Math.cos(0));
console.log(Math.cos(Math.PI));
console.log(Math.cos(Math.PI * 2)); 📌 When to Use
Use Math.cos() for circular motion x-coordinates, rotation calculations, 3D graphics, or phase-shifted animations.
⚠️ Common Mistakes
Confusing sine and cosine usage - cosine gives x-coordinate, sine gives y-coordinate in circular motion.
Not accounting for floating-point precision issues at special angles.
✅ Best Practices
Use Math.cos() and Math.sin() together for circular paths: x = centerX + radius * Math.cos(angle).
For 90-degree phase shifts, cos(x) = sin(x + PI/2).
⚡ Performance Notes
Math.cos() has similar performance to Math.sin(). When both are needed, consider computing them together as they share intermediate calculations in some engines.
🌍 Real World Example
Circular Progress Indicator
Calculate points on a circular path for drawing progress indicators using SVG.
function calculateCircularProgress(percentage, radius = 50, centerX = 50, centerY = 50) {
// Convert percentage to angle (starting from top, clockwise)
const startAngle = -Math.PI / 2;
const endAngle = startAngle + (percentage / 100) * Math.PI * 2;
const startX = centerX + radius * Math.cos(startAngle);
const startY = centerY + radius * Math.sin(startAngle);
const endX = centerX + radius * Math.cos(endAngle);
const endY = centerY + radius * Math.sin(endAngle);
const largeArcFlag = percentage > 50 ? 1 : 0;
return {
svgPath: `M ${startX} ${startY} A ${radius} ${radius} 0 ${largeArcFlag} 1 ${endX} ${endY}`,
endPoint: { x: endX, y: endY }
};
}
console.log(calculateCircularProgress(75));
// Generates SVG arc path for 75% progress