Master JavaScript Math object and number operations for calculations, random numbers, and mathematical algorithms.
The JavaScript Math object is a powerful built-in object that provides mathematical constants and functions for performing complex calculations. Unlike other objects, Math is not a constructor - all properties and methods are static, making it easy to use for mathematical operations. This lesson covers mathematical constants, rounding methods, random number generation, powers and roots, trigonometric functions, and number validation techniques essential for creating robust applications.
The Math object provides access to important mathematical constants and basic operations that are fundamental to many calculations.
Mathematical Constants:
1console.log(Math.PI); // 3.141592653589793
2console.log(Math.E); // 2.718281828459045
3console.log(Math.LN2); // 0.6931471805599453
4console.log(Math.SQRT2); // 1.4142135623730951
5
6// Using constants in calculations
7const radius = 5;
8const circleArea = Math.PI * radius * radius;
9console.log(`Circle area: ${circleArea.toFixed(2)}`); // 78.54
10
11const principal = 1000;
12const rate = 0.05;
13const time = 2;
14const compoundInterest = principal * Math.pow(Math.E, rate * time);
15console.log(`Compound interest: $${compoundInterest.toFixed(2)}`); // $1105.17Basic Math Operations:
1console.log(Math.abs(-42)); // 42
2console.log(Math.max(10, 5, 8)); // 10
3console.log(Math.min(10, 5, 8)); // 5
4
5// Finding maximum and minimum in arrays
6const numbers = [23, 45, 12, 67, 34];
7console.log(Math.max(...numbers)); // 67
8console.log(Math.min(...numbers)); // 12JavaScript provides several methods for rounding numbers, each with different behaviors that are useful in different situations.
Rounding Methods Comparison:
1const num = 4.7;
2const negNum = -4.7;
3
4// Math.round() - rounds to nearest integer
5console.log(Math.round(4.4)); // 4
6console.log(Math.round(4.5)); // 5
7console.log(Math.round(4.6)); // 5
8console.log(Math.round(-4.5)); // -4
9
10// Math.ceil() - always rounds up
11console.log(Math.ceil(4.1)); // 5
12console.log(Math.ceil(4.9)); // 5
13console.log(Math.ceil(-4.9)); // -4
14
15// Math.floor() - always rounds down
16console.log(Math.floor(4.1)); // 4
17console.log(Math.floor(4.9)); // 4
18console.log(Math.floor(-4.1)); // -5
19
20// Math.trunc() - removes decimal part
21console.log(Math.trunc(4.9)); // 4
22console.log(Math.trunc(-4.9)); // -4Custom Rounding Functions:
1// Rounding to specific decimal places
2const price = 19.999;
3console.log(Math.round(price * 100) / 100); // 20 (2 decimal places)
4
5// Safe rounding function
6function roundTo(number, decimals) {
7 const multiplier = Math.pow(10, decimals);
8 return Math.round(number * multiplier) / multiplier;
9}
10
11console.log(roundTo(19.999, 2)); // 20
12console.log(roundTo(Math.PI, 3)); // 3.142JavaScript provides various methods for formatting numbers and validating numeric values, essential for user interfaces and data processing.
Number Formatting Methods:
1const num = 123.456789;
2const bigNum = 1234567.89;
3
4// toFixed() - fixed decimal places (returns string)
5console.log(num.toFixed(2)); // "123.46"
6console.log(num.toFixed(0)); // "123"
7console.log(num.toFixed(4)); // "123.4568"
8
9// toPrecision() - significant digits (returns string)
10console.log(num.toPrecision(4)); // "123.5"
11console.log(num.toPrecision(2)); // "1.2e+2"
12console.log(num.toPrecision(6)); // "123.457"
13
14// toExponential() - scientific notation (returns string)
15console.log(bigNum.toExponential(2)); // "1.23e+6"
16console.log(num.toExponential(3)); // "1.235e+2"Number Parsing and Validation:
1// Number parsing
2console.log(parseInt("123.45")); // 123
3console.log(parseFloat("123.45")); // 123.45
4console.log(Number("123.45")); // 123.45
5console.log(+("123.45")); // 123.45 (unary plus)
6
7// Number validation
8console.log(Number.isNaN(NaN)); // true
9console.log(Number.isFinite(123)); // true
10console.log(Number.isInteger(123)); // true
11console.log(Number.isInteger(123.0)); // true
12console.log(Number.isInteger(123.1)); // false
13
14// Practical formatting examples
15const price = 19.99;
16const percentage = 0.856;
17const largeNumber = 1234567.89;
18
19console.log(`$${price.toFixed(2)}`); // "$19.99"
20console.log(`${(percentage * 100).toFixed(1)}%`); // "85.6%"
21console.log(`${largeNumber.toLocaleString()}`); // "1,234,567.89"Random numbers are essential for games, simulations, testing, and many other applications. JavaScript's Math.random() provides the foundation for generating various types of random values.
Basic Random Number Generation:
1// Math.random() returns 0 to 1 (exclusive of 1)
2console.log(Math.random()); // 0.7834592847...
3
4// Random integer from 0 to 9
5const randomDigit = Math.floor(Math.random() * 10);
6
7// Random integer in range (min to max inclusive)
8function randomInt(min, max) {
9 return Math.floor(Math.random() * (max - min + 1)) + min;
10}
11console.log(randomInt(5, 15)); // Between 5 and 15
12
13// Random float in range
14function randomFloat(min, max) {
15 return Math.random() * (max - min) + min;
16}
17console.log(randomFloat(1.5, 3.8)); // Between 1.5 and 3.8Practical Random Applications:
1// Random boolean (50/50 chance)
2const randomBool = Math.random() < 0.5;
3console.log(`Random boolean: ${randomBool}`);
4
5// Random array element
6const colors = ['red', 'blue', 'green', 'yellow'];
7const randomColor = colors[Math.floor(Math.random() * colors.length)];
8console.log(`Random color: ${randomColor}`);
9
10// Common random patterns
11const diceRoll = Math.floor(Math.random() * 6) + 1; // 1-6
12const coinFlip = Math.random() < 0.5 ? 'heads' : 'tails'; // coin flip
13const rgbValue = Math.floor(Math.random() * 256); // 0-255
14const percentage = Math.floor(Math.random() * 101); // 0-100
15
16// Shuffle array (Fisher-Yates algorithm)
17function shuffle(array) {
18 const result = [...array]; // Don't mutate original
19
20 for (let i = result.length - 1; i > 0; i--) {
21 const j = Math.floor(Math.random() * (i + 1));
22 [result[i], result[j]] = [result[j], result[i]];
23 }
24
25 return result;
26}
27
28const deck = ['A', 'K', 'Q', 'J', '10', '9'];
29console.log('Shuffled deck:', shuffle(deck));Mathematical operations involving powers and roots are common in scientific calculations, game physics, and data analysis.
Power Functions:
1// Power functions
2console.log(Math.pow(2, 8)); // 256 (2^8)
3console.log(2 ** 8); // 256 (ES2016 exponentiation operator)
4console.log(Math.pow(3, 4)); // 81 (3^4)
5
6// Square root
7console.log(Math.sqrt(16)); // 4
8console.log(Math.sqrt(2)); // 1.4142135623730951
9console.log(Math.sqrt(25)); // 5
10
11// Cube root
12console.log(Math.cbrt(27)); // 3
13console.log(Math.cbrt(8)); // 2
14console.log(Math.cbrt(125)); // 5
15
16// Nth root using power
17function nthRoot(number, n) {
18 return Math.pow(number, 1/n);
19}
20console.log(nthRoot(32, 5)); // 2 (5th root of 32)
21console.log(nthRoot(64, 3)); // 4 (cube root of 64)Practical Mathematical Applications:
1// Hypotenuse calculation (Pythagorean theorem)
2console.log(Math.hypot(3, 4)); // 5 (3-4-5 triangle)
3console.log(Math.hypot(5, 12)); // 13 (5-12-13 triangle)
4
5// Practical applications
6function distance(x1, y1, x2, y2) {
7 return Math.hypot(x2 - x1, y2 - y1);
8}
9
10function compoundInterest(principal, rate, time) {
11 return principal * Math.pow(1 + rate, time);
12}
13
14function circleArea(radius) {
15 return Math.PI * Math.pow(radius, 2);
16}
17
18// Examples
19console.log('Distance:', distance(0, 0, 3, 4)); // 5
20console.log('Compound:', compoundInterest(1000, 0.05, 10)); // 1628.89
21console.log('Circle area:', circleArea(10).toFixed(2)); // 314.16
22
23// Performance tip: x * x is faster than Math.pow(x, 2)
24const x = 5;
25console.log(x * x); // 25 (faster)
26console.log(Math.pow(x, 2)); // 25 (slower)Trigonometric functions are essential for game development, animations, physics simulations, and geometric calculations.
Trigonometric Functions:
1// Trigonometric functions work with radians
2const degrees45 = 45;
3const radians45 = degrees45 * (Math.PI / 180);
4
5console.log(Math.sin(radians45)); // 0.7071067811865475
6console.log(Math.cos(radians45)); // 0.7071067811865476
7console.log(Math.tan(radians45)); // 0.9999999999999999 (~1)
8
9// Inverse trigonometric functions (return radians)
10console.log(Math.asin(0.5)); // 0.5235987755982989 (30°)
11console.log(Math.acos(0.5)); // 1.0471975511965979 (60°)
12console.log(Math.atan(1)); // 0.7853981633974483 (45°)
13
14// Utility functions for conversion
15function toRadians(degrees) {
16 return degrees * (Math.PI / 180);
17}
18
19function toDegrees(radians) {
20 return radians * (180 / Math.PI);
21}Number Validation and Edge Cases:
1// Number validation methods
2console.log(Number.isNaN(NaN)); // true
3console.log(Number.isNaN("hello")); // false (not a number type)
4console.log(isNaN("hello")); // true (coerces to NaN - avoid this)
5
6console.log(Number.isFinite(42)); // true
7console.log(Number.isFinite(Infinity)); // false
8console.log(Number.isFinite("42")); // false (string)
9
10// Safe integer checking
11console.log(Number.isSafeInteger(42)); // true
12console.log(Number.isSafeInteger(Math.pow(2, 53))); // false
13console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
14
15// Edge cases and special values
16console.log(1/0); // Infinity
17console.log(-1/0); // -Infinity
18console.log(0/0); // NaN
19console.log(Math.sqrt(-1)); // NaN
20
21// Floating point precision issues
22console.log(0.1 + 0.2); // 0.30000000000000004
23console.log(0.1 + 0.2 === 0.3); // false!
24
25// Solutions for precision issues
26function nearlyEqual(a, b, epsilon = 0.000001) {
27 return Math.abs(a - b) < epsilon;
28}
29
30function addDecimals(a, b, decimals = 2) {
31 const multiplier = Math.pow(10, decimals);
32 return Math.round((a + b) * multiplier) / multiplier;
33}
34
35console.log(nearlyEqual(0.1 + 0.2, 0.3)); // true
36console.log(addDecimals(0.1, 0.2)); // 0.3Your progress is saved in this browser, on this device only.