JavaScript: Math Operators
Math Operators
Basic arithmetic.
// plus, add console.log((3 + 4) === 7);
// minus, substraction console.log((3 - 4) === -1);
// negation console.log(-(3 + 4) === -7); console.log(-(-3) === 3);
// multiply console.log(3 * 4 === 12);
// divide console.log(3 / 4 === 0.75);
x % y
-
Modular arithmetic. Get remainder of x divided by y.
Both x and y can be decimal with fraction part.// remainder (mod) console.log(10 % 3 === 1);
console.log(7 % 2); // 1 console.log(7.4 % 2); // 1.4000000000000004 console.log(7 % 3.4); // 0.20000000000000018
x ** n
-
Raise x to n's power. (JS2016)
Same as
Math.pow(x, n)
.// power console.log(2 ** 3 === 8);
Math Methods
Math.floor(x / y)
-
Get integer quotient.
[see Math]
console.log(Math.floor(7 / 2) === 3);
Math.sqrt(x)
-
Square root. [see Math]
console.log(Math.sqrt(4) === 2);
Math.cbrt(x)
-
Cube root.
// cube root console.log(Math.cbrt(8) === 2);
x ** (1/n)
-
nth root. (JS2016) Same as
Math.pow(x, 1/n)
// 4th root console.log(Math.pow(16, 1 / 4) === 2);