Assignment operators (JavaScript)

An assignment operator assigns a value to its left operand based on the value of its right operand. The basic assignment operator is equal (=). The other assignment operators are shorthand for another operation plus the assignment.

Operator Meaning Description
x = y x = y Assigns the value of y to x.
x += y x = x + y Assigns the result of x plus y tox.
x -= y x = x - y Assigns the result of x minus y tox.
x *= y x = x * y Assigns the result of x times y tox.
x /= y x = x / y Assigns the result of x divided by y tox.
x %= y x = x % y Assigns the result of x modulo y tox.
x &=y x = x & y Assigns the result of x AND y tox.
X |=y x =x | y Assigns the result of x OR y tox.
x ^=y x = x ^ y Assigns the result of x XOR y tox.
x <<= y x = x << y Assigns the result of x shifted left by y tox.
x >>= y x = x >> y Assigns the result of x shifted right (sign preserved) by y tox.
x >>>= y x = x >>> y Assigns the result of x shifted right by y tox.

Examples

This example exercises the = and += operators. Each loop is functionally the same.
function p(stuff) {
	print("<<<" + stuff + ">>>");
}

p("start =");
var x = 0.1;
do {
	p("x = " + x);
	x = x + 0.1;
} while(x < 1.0)

p("start +=");
var x = 0.1;
do {
	p("x = " + x);
	x += 0.1;
} while(x < 1.0)

This example exercises the assignment operators that also perform arithmetic operations.

function p(stuff) {
	print("<<<" + stuff + ">>>");
}

var x1 = 1.0, x2 = 1.0, x3 = 1.0, x4 = 1.0;
var y = 0.25;
for(var i = 0; i < 5; i++) {
	x1 += y;
	x2 -= y;
	x3 *= y;
	x4 /= y;
}
p("x1 += y: " + x1);
p("x2 -= y: " + x2);
p("x3 *= y: " + x3);
p("x4 /= y: " + x4);