JavaScript: Assignment Operators
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 ifx
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 Property, 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 ifBoolean(x)
eval tofalse
. [see 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 Property, 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 ifBoolean(x)
eval totrue
. [see 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);