Math.sin()
ES1+Returns the sine of a number (in radians).
Syntax
Math.sin(x)Parameters
x number A number in radians
Return Value
The sine of the given number
Examples
console.log(Math.sin(0));
console.log(Math.sin(Math.PI / 2));
console.log(Math.sin(Math.PI)); 📌 When to Use
Use Math.sin() for animations, wave patterns, circular motion, physics simulations, or audio waveform generation.
⚠️ Common Mistakes
Forgetting to convert degrees to radians: radians = degrees * (Math.PI / 180).
Expecting Math.sin(Math.PI) to return exactly 0 - floating point returns a very small number instead.
✅ Best Practices
Create a degToRad helper function: const degToRad = (deg) => deg * (Math.PI / 180).
For animations, use time-based input: Math.sin(Date.now() / 1000) for smooth 1Hz oscillation.
⚡ Performance Notes
Trigonometric functions are CPU-intensive. For performance-critical code with many calculations, consider pre-computing values into lookup tables.
🌍 Real World Example
Smooth Hover Animation
Create a smooth floating animation effect using sine waves for UI elements.
function createFloatingAnimation(element, options = {}) {
const { amplitude = 10, frequency = 1, startTime = Date.now() } = options;
function animate() {
const elapsed = (Date.now() - startTime) / 1000;
const offset = Math.sin(elapsed * frequency * Math.PI * 2) * amplitude;
element.style.transform = `translateY(${offset}px)`;
requestAnimationFrame(animate);
}
animate();
}
// Usage: createFloatingAnimation(document.querySelector('.floating-icon'));
// Creates a smooth up-and-down floating effect