JS: Math Operators

By Xah Lee. Date: . Last updated: .

Basic Arithmetic

// plus, add
console.assert((3 + 4) === 7);
// minus, substraction
console.assert((3 - 4) === -1);
// negation
console.assert(-(-3) === 3);
// multiply
console.assert(3 * 4 === 12);
// divide
console.assert(3 / 4 === 0.75);

Mod (Remainder)

console.assert(7 % 2 === 1);
console.assert(7.4 % 2 === 1.4000000000000004);
console.assert(7 % 3.4 === 0.20000000000000018);

Ceiling, Floor, Round

console.assert(Math.floor(3.5847) === 3);
console.assert(Math.ceil(3.5847) === 4);
// round towards positive infinity

console.assert(Math.round(3.54) === 4);
console.assert(Math.round(3.5) === 4);

// round towards positive infinity
console.assert(Math.round(-3.54) === -4);
console.assert(Math.round(-3.5) === -3);

Power (Exponential)

// power
console.assert(2 ** 3 === 8);

// same as
console.assert(Math.pow(2, 3) === 8);

Root

// square root
console.assert(Math.sqrt(4) === 2);
// cube root
console.assert(Math.cbrt(8) === 2);
// 4th root
console.assert(Math.pow(16, 1 / 4) === 2);

JavaScript. Operators

JavaScript. Number