Team LiB   Previous Section   Next Section

5.9 Assignment Operators

As we saw in the discussion of variables in Chapter 4, = is used in JavaScript to assign a value to a variable. For example:

i = 0

While you might not normally think of such a line of JavaScript as an expression that can be evaluated, it is in fact an expression and, technically speaking, = is an operator.

The = operator expects its lefthand operand to be either a variable, the element of an array, or a property of an object. It expects its righthand operand to be an arbitrary value of any type. The value of an assignment expression is the value of the righthand operand. As a side effect, the = operator assigns the value on the right to the variable, element, or property on the left, so that future uses of the variable, element, or property refer to the value.

Because = is defined as an operator, you can include it in more complex expressions. For example, you can assign and test a value in the same expression with code like this:

(a = b) == 0

If you do this, be sure you are clear on the difference between the = and == operators!

The assignment operator has right-to-left associativity, which means that when multiple assignment operators appear in an expression, they are evaluated from right to left. Thus, you can write code like this to assign a single value to multiple variables:

i = j = k = 0; 

Remember that each assignment expression has a value that is the value of the righthand side. So in the above code, the value of the first assignment (the rightmost one) becomes the righthand side for the second assignment (the middle one), and this value becomes the righthand side for the last (leftmost) assignment.

5.9.1 Assignment with Operation

Besides the normal = assignment operator, JavaScript supports a number of other assignment operators that provide shortcuts by combining assignment with some other operation. For example, the += operator performs addition and assignment. The following expression:

total += sales_tax 

is equivalent to this one:

total = total + sales_tax 

As you might expect, the += operator works for numbers or strings. For numeric operands, it performs addition and assignment; for string operands, it performs concatenation and assignment.

Similar operators include -= , *=, &=, and so on. Table 5-2 lists them all. In most cases, the expression:


op= b

where op is an operator, is equivalent to the expression:

a = a 

op b 

These expressions differ only if a contains side effects such as a function call or an increment operator.

Table 5-2. Assignment operators





a += b

a = a + b


a -= b

a = a - b


a *= b

a = a * b


a /= b

a = a / b


a %= b

a = a % b


a <<= b

a = a << b


a >>= b

a = a >> b


a >>>= b

a = a >>> b


a &= b

a = a & b


a |= b

a = a | b


a ^= b

a = a ^ b

    Team LiB   Previous Section   Next Section