Recall from earlier in this chapter that assignment is itself an expression, so the value
that’s returned is the value that’s being assigned. This allows you to chain assign‐
ments, as well as perform assignments within other expressions:
let
v
,
v0
;
v
=
v0
=
9.8
;
// chained assignment; first v0 gets
// the value 9.8, and then v gets the
// value 9.8
const
nums
=
[
3
,
5
,
15
,
7
,
5
];
let
n
,
i
=
0
;
// note the assignment in the while condition; n
// takes on the value of nums[i], and the whole
// expression also evalutes to that value, allowing
// a numeric comparison:
while
((
n
=
nums
[
i
])
<
10
,
i
++
<
nums
.
length
) {
console.log(
`Number less than 10:
${
n
}
.`
);
}
console.log(
`Number greater than 10 found:
${
n
}
.`
);
console.log(
`
${
nums
.
length
}
numbers remain.`
);
Notice in the second example, we have to use a grouping operator because assign‐
ment has a lower precedence than relational operators.
In addition to the ordinary assignment operators, there are convenience assignment
operators that perform an operation and assignment in one step. Just as with the
ordinary assignment operator, these operators evaluate to the final assignment value.
summarizes these convenience assignment operators.
Table 5-9. Assignment with operation
Operator
Equivalent
x += y
x = x + y
x -= y
x = x - y
x *= y
x = x * y
x /= y
x = x / y
x %= y
x = x % y
x <<= y
x = x << y
x >>= y
x = x >> y
x >>>= y x = x >>> y
Grouping Operator | 97