Math Object and Operations in JavaScript
Introduction
The Math object provides mathematical constants and methods for performing mathematical operations. It’s essential for calculations, random number generation, and numerical operations. In this article, you’ll learn all major Math methods and constants with practical examples.
Math Constants
Common Constants
// Mathematical constants
console.log(Math.PI); // 3.141592653589793
console.log(Math.E); // 2.718281828459045
console.log(Math.LN2); // 0.6931471805599453
console.log(Math.LN10); // 2.302585092994046
console.log(Math.LOG2E); // 1.4426950408889634
console.log(Math.LOG10E); // 0.4342944819032518
console.log(Math.SQRT1_2); // 0.7071067811865476
console.log(Math.SQRT2); // 1.4142135623730951
// Practical example: Calculate circle area
function circleArea(radius) {
return Math.PI * radius * radius;
}
console.log(circleArea(5)); // 78.53981633974483
Rounding Methods
Math.round()
// Round to nearest integer
console.log(Math.round(4.4)); // 4
console.log(Math.round(4.5)); // 5
console.log(Math.round(4.6)); // 5
console.log(Math.round(-4.5)); // -4
// Practical example: Round to decimal places
function roundTo(num, decimals) {
const factor = Math.pow(10, decimals);
return Math.round(num * factor) / factor;
}
console.log(roundTo(3.14159, 2)); // 3.14
console.log(roundTo(10.555, 2)); // 10.56
Math.floor()
// Round down to nearest integer
console.log(Math.floor(4.9)); // 4
console.log(Math.floor(4.1)); // 4
console.log(Math.floor(-4.1)); // -5
// Practical example: Get integer part
function getIntegerPart(num) {
return Math.floor(num);
}
console.log(getIntegerPart(3.7)); // 3
console.log(getIntegerPart(-3.7)); // -4
Math.ceil()
// Round up to nearest integer
console.log(Math.ceil(4.1)); // 5
console.log(Math.ceil(4.9)); // 5
console.log(Math.ceil(-4.9)); // -4
// Practical example: Calculate pages needed
function calculatePages(items, itemsPerPage) {
return Math.ceil(items / itemsPerPage);
}
console.log(calculatePages(25, 10)); // 3
console.log(calculatePages(20, 10)); // 2
Math.trunc()
// Remove decimal part
console.log(Math.trunc(4.9)); // 4
console.log(Math.trunc(-4.9)); // -4
console.log(Math.trunc(4.1)); // 4
// Practical example: Get integer without rounding
function toInteger(num) {
return Math.trunc(num);
}
console.log(toInteger(3.7)); // 3
console.log(toInteger(-3.7)); // -3
Absolute Value and Sign
Math.abs()
// Get absolute value
console.log(Math.abs(5)); // 5
console.log(Math.abs(-5)); // 5
console.log(Math.abs(0)); // 0
// Practical example: Calculate difference
function difference(a, b) {
return Math.abs(a - b);
}
console.log(difference(10, 3)); // 7
console.log(difference(3, 10)); // 7
Math.sign()
// Get sign of number
console.log(Math.sign(5)); // 1
console.log(Math.sign(-5)); // -1
console.log(Math.sign(0)); // 0
console.log(Math.sign(-0)); // -0
// Practical example: Direction indicator
function getDirection(value) {
const sign = Math.sign(value);
if (sign > 0) return 'positive';
if (sign < 0) return 'negative';
return 'zero';
}
console.log(getDirection(10)); // 'positive'
console.log(getDirection(-5)); // 'negative'
Power and Root Operations
Math.pow()
// Raise to power
console.log(Math.pow(2, 3)); // 8
console.log(Math.pow(5, 2)); // 25
console.log(Math.pow(10, -1)); // 0.1
// Practical example: Calculate compound interest
function compoundInterest(principal, rate, years) {
return principal * Math.pow(1 + rate, years);
}
console.log(compoundInterest(1000, 0.05, 10)); // 1628.89
Math.sqrt()
// Square root
console.log(Math.sqrt(4)); // 2
console.log(Math.sqrt(9)); // 3
console.log(Math.sqrt(2)); // 1.4142135623730951
// Practical example: Calculate hypotenuse
function hypotenuse(a, b) {
return Math.sqrt(a * a + b * b);
}
console.log(hypotenuse(3, 4)); // 5
console.log(hypotenuse(5, 12)); // 13
Math.cbrt()
// Cube root
console.log(Math.cbrt(8)); // 2
console.log(Math.cbrt(27)); // 3
console.log(Math.cbrt(-8)); // -2
// Practical example: Calculate volume
function cubeVolume(sideLength) {
return Math.pow(sideLength, 3);
}
function cubeSideFromVolume(volume) {
return Math.cbrt(volume);
}
console.log(cubeSideFromVolume(27)); // 3
Trigonometric Functions
Basic Trigonometry
// Sine, cosine, tangent (radians)
console.log(Math.sin(Math.PI / 2)); // 1
console.log(Math.cos(0)); // 1
console.log(Math.tan(Math.PI / 4)); // 1
// Convert degrees to radians
function toRadians(degrees) {
return degrees * (Math.PI / 180);
}
// Convert radians to degrees
function toDegrees(radians) {
return radians * (180 / Math.PI);
}
console.log(Math.sin(toRadians(90))); // 1
console.log(toDegrees(Math.PI)); // 180
Inverse Trigonometric Functions
// Arcsine, arccosine, arctangent
console.log(Math.asin(1)); // 1.5707963267948966 (ฯ/2)
console.log(Math.acos(0)); // 1.5707963267948966 (ฯ/2)
console.log(Math.atan(1)); // 0.7853981633974483 (ฯ/4)
// Practical example: Calculate angle
function calculateAngle(x, y) {
return Math.atan2(y, x);
}
console.log(calculateAngle(1, 1)); // 0.7853981633974483 (45 degrees)
Logarithmic Functions
Basic Logarithms
// Natural logarithm
console.log(Math.log(Math.E)); // 1
console.log(Math.log(1)); // 0
// Base 10 logarithm
console.log(Math.log10(100)); // 2
console.log(Math.log10(1000)); // 3
// Base 2 logarithm
console.log(Math.log2(8)); // 3
console.log(Math.log2(16)); // 4
// Practical example: Calculate pH
function calculatePH(concentration) {
return -Math.log10(concentration);
}
console.log(calculatePH(0.0001)); // 4
Exponential Functions
Math.exp()
// e raised to power
console.log(Math.exp(0)); // 1
console.log(Math.exp(1)); // 2.718281828459045
console.log(Math.exp(2)); // 7.3890560989306495
// Practical example: Calculate exponential growth
function exponentialGrowth(initial, rate, time) {
return initial * Math.exp(rate * time);
}
console.log(exponentialGrowth(100, 0.1, 5)); // 164.87...
Min and Max
Math.min() and Math.max()
// Find minimum value
console.log(Math.min(5, 2, 8, 1)); // 1
console.log(Math.min()); // Infinity
// Find maximum value
console.log(Math.max(5, 2, 8, 1)); // 8
console.log(Math.max()); // -Infinity
// Practical example: Find range
function findRange(arr) {
return {
min: Math.min(...arr),
max: Math.max(...arr),
range: Math.max(...arr) - Math.min(...arr)
};
}
console.log(findRange([3, 1, 4, 1, 5, 9]));
// { min: 1, max: 9, range: 8 }
Random Numbers
Math.random()
// Generate random number between 0 and 1
console.log(Math.random()); // 0.123456... (varies)
// Practical example: Random integer
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 10)); // Random number 1-10
// Practical example: Random choice
function randomChoice(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
console.log(randomChoice(['apple', 'banana', 'orange']));
// Practical example: Shuffle array
function shuffle(arr) {
const copy = [...arr];
for (let i = copy.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[copy[i], copy[j]] = [copy[j], copy[i]];
}
return copy;
}
console.log(shuffle([1, 2, 3, 4, 5]));
Real-World Examples
Example 1: Distance Calculator
// Calculate distance between two points
function distance(x1, y1, x2, y2) {
const dx = x2 - x1;
const dy = y2 - y1;
return Math.sqrt(dx * dx + dy * dy);
}
console.log(distance(0, 0, 3, 4)); // 5
console.log(distance(1, 1, 4, 5)); // 5
Example 2: Statistics Calculator
// Calculate statistics
function statistics(arr) {
const sum = arr.reduce((a, b) => a + b, 0);
const mean = sum / arr.length;
const variance = arr.reduce((sum, val) => {
return sum + Math.pow(val - mean, 2);
}, 0) / arr.length;
const stdDev = Math.sqrt(variance);
return {
mean: Math.round(mean * 100) / 100,
variance: Math.round(variance * 100) / 100,
stdDev: Math.round(stdDev * 100) / 100,
min: Math.min(...arr),
max: Math.max(...arr)
};
}
console.log(statistics([1, 2, 3, 4, 5]));
// { mean: 3, variance: 2, stdDev: 1.41, min: 1, max: 5 }
Example 3: Percentage Calculator
// Calculate percentages
function percentage(value, total) {
return Math.round((value / total) * 100 * 100) / 100;
}
function percentageOf(percent, total) {
return Math.round((percent / 100) * total * 100) / 100;
}
console.log(percentage(25, 100)); // 25
console.log(percentageOf(20, 50)); // 10
Example 4: Angle and Rotation
// Calculate rotation angle
function rotationAngle(x1, y1, x2, y2) {
const angle = Math.atan2(y2 - y1, x2 - x1);
return Math.round(toDegrees(angle) * 100) / 100;
}
function toDegrees(radians) {
return radians * (180 / Math.PI);
}
console.log(rotationAngle(0, 0, 1, 1)); // 45
console.log(rotationAngle(0, 0, 0, 1)); // 90
Common Mistakes to Avoid
Mistake 1: Forgetting Radians for Trigonometry
// โ Wrong - Using degrees directly
console.log(Math.sin(90)); // 0.8939966636005579 (wrong!)
// โ
Correct - Convert to radians
console.log(Math.sin(Math.PI / 2)); // 1
Mistake 2: Not Handling Edge Cases
// โ Wrong - No edge case handling
function divide(a, b) {
return a / b;
}
divide(10, 0); // Infinity
// โ
Correct - Handle edge cases
function divide(a, b) {
if (b === 0) throw new Error('Division by zero');
return a / b;
}
Mistake 3: Precision Issues
// โ Wrong - Floating point precision
console.log(0.1 + 0.2 === 0.3); // false
// โ
Correct - Use epsilon comparison
function almostEqual(a, b, epsilon = 0.0001) {
return Math.abs(a - b) < epsilon;
}
console.log(almostEqual(0.1 + 0.2, 0.3)); // true
Summary
Math object provides essential operations:
- Rounding: round, floor, ceil, trunc
- Power/Root: pow, sqrt, cbrt
- Trigonometry: sin, cos, tan, asin, acos, atan
- Logarithms: log, log10, log2
- Exponential: exp
- Min/Max: min, max
- Random: random
- Use for calculations and numerical operations
- Remember radians for trigonometry
- Handle floating-point precision issues
- Combine methods for complex calculations
Related Resources
Next Steps
Continue your learning journey:
- Object Methods: keys, values, entries, assign
- Date and Time Handling in JavaScript
- Number Methods and Formatting
- Array Methods: Complete Reference
Comments