Trigonometric Functions in JavaScript
You'll learn how to use JavaScript's built-in trigonometric functions and the critical detail about radians vs. degrees.
The Core Concept
JavaScript provides three main trigonometric functions through the Math object: Math.sin(), Math.cos(), and Math.tan(). These calculate the sine, cosine, and tangent of an angle, respectively. The crucial detail: all these functions expect angles in radians, not degrees.
If you're used to thinking in degrees (like 90° or 180°), you'll need to convert first. Remember that 360 degrees = 2π radians, so to convert degrees to radians, multiply by (Math.PI / 180).
Using Trigonometric Functions
// For a 90-degree angle
const degrees = 90;
const radians = degrees * (Math.PI / 180);
Math.sin(radians); // 1 (sine of 90°)
Math.cos(radians); // ~0 (cosine of 90°)
Math.tan(radians); // Very large number (tangent of 90° approaches infinity)
// Common angles in radians
Math.sin(0); // 0
Math.sin(Math.PI / 2); // 1 (90 degrees)
Math.cos(0); // 1
Math.cos(Math.PI); // -1 (180 degrees)
Math.tan(Math.PI / 4); // 1 (45 degrees)
Practical Example
// Calculate position on a circle
function getCirclePoint(radius, angleDegrees) {
const radians = angleDegrees * (Math.PI / 180);
return {
x: radius * Math.cos(radians),
y: radius * Math.sin(radians)
};
}
getCirclePoint(10, 45); // Point at 45° on circle with radius 10
Key Takeaway: JavaScript's Math.sin(), Math.cos(), and Math.tan() work exclusively with radians, not degrees—always convert using degrees * (Math.PI / 180) when needed.