JS: Assignment Operators

By Xah Lee. Date: . Last updated: .

Assignment Operators

`var = val`
assign val to var, and return val [see let Declaration]
```let zz;
console.log(((zz = 3) + 1) === 4);```

Increment / Decrement Assignment

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

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 Nullish assignment operator.
Assigns y to x if `x` is null or undefined .

left-hand-side must be assignable, such as a variable or property.

typically used for assigning a value to a object property but only when the property does not exist. [see Get Set Property]

```let x;
// if x has no value (null or undefined), give it one
x ??= 4;
console.log(x === 4);```
```let x = false;
// if x has no value (null or undefined), give it one
x ??= 4;
console.log((x === 4) === false);
// assignment failed, because x do have a value already
```
`x ||= y`
(JS2021) LOGICAL OR assignment operator.
Assigns y to x if `Boolean(x)` eval to `false`. [see JS: Boolean: true, false]

left-hand-side must be assignable, such as a variable or property.

typically used for assigning a value to a object property but only when the property does not exist or has no βvalidβ value (e.g. `false`, null or undefined). [see Get Set Property]

```let x;
// if x has no value (null or undefined), give it one
x ||= 4;
console.log(x === 4);```
`x &&= y`
(JS2021) LOGICAL AND assignment operator.
Assigns y to x if `Boolean(x)` eval to `true`. [see JS: Boolean: true, false]

left-hand-side must be assignable, such as a variable or property.

```let x = 3;
x &&= 4;
// assignment successful, because x eval to true
console.log(x === 4);```
```let x;
x &&= 4;
// assignment fails because x was false
console.log(x === undefined);```