JavaScript - assignment operators example
The example below shows the usage of assignment and compound assignment operators:
- = Assignment operator
- += Addition AND assignment operator
- -= Subtraction AND assignment operator
- *= Multiply AND assignment operator
- /= Division AND assignment operator
- **= Exponent AND assignment operator
- %= Modulo AND assignment operator
- &&= Logical AND assignment operator
- ||= Logical OR assignment operator
- ??= Nullish coalescing assignment operator
var X = 25; var txt; txt = "X = " + X + "<br>"; //Addition AND assignment operator X += 5; txt = txt + "X += 5; makes X = " + X + "<br>"; //Subtraction AND assignment operator X -= 8; txt = txt + "X -= 8; makes X = "+ X + "<br>"; //Multiply AND assignment operator X *= 4; txt = txt + "X *= 4; makes X = "+ X + "<br>"; //Division AND assignment operator X /= 2; txt = txt + "X /= 2; makes X = "+ X + "<br>"; //Exponent AND assignment operator X **= 2; txt = txt + "X **= 2; makes X = "+ X + "<br>"; //Modulo AND assignment operator X %= 5; txt = txt + "X %= 5; makes X = "+ X + "<br>";
The output (value of txt) after running above script will be:
X = 25 X += 5; makes X = 30 X -= 8; makes X = 22 X *= 4; makes X = 88 X /= 2; makes X = 44 X **= 2; makes X = 1936 X %= 5; makes X = 1
Logical AND assignment operator (&&=)
The logical AND assignment (x &&= y) operator only assigns if x is truthy (a value that is considered true in a Boolean context).
let a = 1; let b = 0; var txt; //10 will be assigned to a a &&= 10; //no assignment is done to b b &&= 10; txt = "a = " + a + "<br>"; txt = txt + "b = " + b + "<br>";
The output (value of txt) after running above script will be:
a = 10 b = 0
Logical OR assignment operator (||=)
The logical OR assignment (x ||= y) operator only assigns if x is falsy (a value that is considered false in a Boolean context).
let a = 1; let b = 0; var txt; //no assignment is done to a a ||= 10; //10 will be assigned to b b ||= 10; txt = "a = " + a + "<br>"; txt = txt + "b = " + b + "<br>";
The output (value of txt) after running above script will be:
a = 1 b = 10
Nullish coalescing assignment operator (??=)
The nullish coalescing assignment (x ??= y) operator only assigns if x is null or undefined.
let A = null; let B = undefined; let C = "Hello"; var txt; //10 is assigned to a A ??= 10; //10 is assigned to b B ??= 10; //no assignment is done to c C ??= 10; txt = "A = " + A + "<br>"; txt = txt + "B = " + B + "<br>"; txt = txt + "C = " + C + "<br>";
The output (value of txt) after running above script will be:
A = 10 B = 10 C = Hello
❮ JavaScript - Operators