JavaScript: Operators

By Xah Lee. Date: . Last updated: .

Common Math Operators

Basic arithmetic.

// basic arithmetic
3 + 4;      // 7
3 - 4;      // -1
3 * 4;      // 12
3 / 4;      // 0.75

// negation
-(3+4);     // -7
Math.floor( x / y)
Get integer quotient. Math.floor(7/2) === 3 [see Math]
x % y
Get remainder of x divided by y. (aka modular arithmetic)
Both x and y can be decimal with fraction part.
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).
Math.sqrt(x)
Square root. [see Math]
Math.cbrt(x)
Cube root.
x ** (1/n)
n's root. (JS2016) Same as Math.pow(x, 1/n)

Assignment Operators

Assignment returns a value. It returns the value of the right-hand-side.

// assignment returns a value
let zz;
console.log( ( zz = 3) + 1 );
// 4

Compound Assignment Operators

x += y
same as x = x + y
x -= y
same as x = x - y
x *= y
same as x = x * y
x /= y
same as x = x / y
x %= y
same as x = x % y

Logical Assignment Operators

x &&= y
(JS2021) Logical AND assignment operator.
Assigns y to x if Boolean(x) eval to true.
let x = 3;
x &&= 4;
console.log(x === 4); // true
x ||= y
(JS2021) Logical OR assignment operator.
Assigns y to x if Boolean(x) eval to false.
x ??= y
(JS2021) Logical Nullish assignment operator.
Assigns y to x if x is null or undefined .

Increment / Decrement Assignment

++x
same as x=x+1 (returns new value)
--x
same as x=x-1 (returns new value)
x++
like x=x+1 but returns old value
x--
like x=x-1 but returns old value