More on JavaScript Operators
Assignment operators
An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal (=
), which assigns the value of its right operand to its left operand. That is,
x = y
assigns the value of y
to x
.
There are also compound assignment operators that are shorthand for the operations listed in the following table:
Name | Shorthand operator | Meaning |
---|---|---|
Assignment | x = y |
x = y |
Addition assignment | x += y |
x = x + y |
Subtraction assignment | x -= y |
x = x - y |
Multiplication assignment | x *= y |
x = x * y |
Division assignment | x /= y |
x = x / y |
Remainder assignment | x %= y |
x = x % y |
Exponentiation assignment | x **= y |
x = x ** y |
Left shift assignment | x <<= y |
x = x << y |
Right shift assignment | x >>= y |
x = x >> y |
Unsigned right shift assignment | x >>>= y |
x = x >>> y |
Bitwise AND assignment | x &= y |
x = x & y |
Bitwise XOR assignment | x ^= y |
x = x ^ y |
Bitwise OR assignment | x |= y |
x = x | y |
Logical AND assignment | x &&= y |
x && (x = y) |
Logical OR assignment | x ||= y |
x || (x = y) |
Logical nullish assignment | x ??= y |
x ?? (x = y) |
Return value and chaining
Like most expressions, assignments like x = y have a return value. It can be retrieved by e.g. assigning the expression or logging it:
const z = (x = y); // Or equivalently: const z = x = y; console.log(z); // Log the return value of the assignment x = y. console.log(x = y); // Or log the return value directly.
The return value matches the expression to the right of the =
sign in the "Meaning" column of the table above. That means that (x = y)
returns y
, (x += y)
returns the resulting sum x + y
,
(x **= y)
returns the resulting power x ** y
, and so on.
In the case of logical assignments, (x &&= y)
, (x ||= y)
, and (x ??= y)
, the return value is that of the logical operation without the assignment, so x && y
,
x || y
, and
Note that the return values are always based on the operands' values before the operation.
When chaining these expressions, each assignment is evaluated right-to-left. Consider these examples:
w = z = x = y
is equivalent tow = (z = (x = y))
orx = y; z = y; w = y
z += x *= y
is equivalent toz += (x *= y)
ortmp = x * y; x *= y; z += tmp
(except without thetmp
).
Destructuring
For more complex assignments, the destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.
var foo = ['one', 'two', 'three']; // without destructuring var one = foo[0]; var two = foo[1]; var three = foo[2]; // with destructuring var [one, two, three] = foo;