Episode 10 of 46

Mathematical Operations in JavaScript

Learn all the math operators and the built-in Math object for advanced calculations.

JavaScript supports all standard mathematical operations plus a powerful built-in Math object.

Basic Operators

let a = 10, b = 3;

console.log(a + b);   // 13 — Addition
console.log(a - b);   // 7  — Subtraction
console.log(a * b);   // 30 — Multiplication
console.log(a / b);   // 3.333... — Division
console.log(a % b);   // 1  — Modulus (remainder)
console.log(a ** b);  // 1000 — Exponentiation (10³)

Operator Precedence

Just like in maths, multiplication and division happen before addition and subtraction:

let result = 5 + 3 * 2;    // 11 (not 16)
let result2 = (5 + 3) * 2; // 16 (parentheses first)

The Math Object

// Rounding
Math.round(4.5);    // 5
Math.ceil(4.1);     // 5 (round up)
Math.floor(4.9);    // 4 (round down)
Math.trunc(4.9);    // 4 (remove decimal)

// Min and Max
Math.max(1, 5, 3);  // 5
Math.min(1, 5, 3);  // 1

// Power and Square Root
Math.pow(2, 8);     // 256
Math.sqrt(64);      // 8

// Absolute value
Math.abs(-42);      // 42

// Constants
Math.PI;            // 3.14159...

// Random number between 0 and 1
Math.random();      // e.g. 0.7362...

Generating Random Integers

// Random integer between 1 and 10
let random = Math.floor(Math.random() * 10) + 1;

// Random integer between min and max
function randomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomInt(1, 100));