Es2021
introduced Logical
Operators and Assignment
Expressions as part of the latest features.
Before ES2021, Javascript has the following logical operators.
These logical operators are applied to variables or operands.
&&
| And | evaluates true if both are true | true && true returns true|
|||
| OR | evaluates true if one of is true | true && false returns true|
|! | NOT | evaluates true if operand is false | !true returns false|The above operators only check the logical
operation and return true or false
based on operands.
It introduced new features and syntax to existing logical operators ES2021
.
What do logical operators and assignment expressions do?
The following operators are introduced in ES2021.
- logical AND operator assignment expression (&&=)
- logical OR operator assignment expression (||=)
- logical Double question operator assignment expression (??=)
logical AND operator assignment expression (&&=)
logical
AND assignment
expression apply to two variables or operands of a javascript expression.
if one of the value or operand expressions returns a truthy result, Then this operator assigns a second variable value to the first variable
Here is an example
let variable1 = 1;
let variable2 = 12;
variable1 &&= variable2;
console.log(variable1) // outputs 12
In the above example, variable1 is the truthy
value, the truthy
value is a number or true, etc.
The above code is equal to
let variable1 = 1;
let variable2 = 12;
if(variable1){
variable1 = variable2;
}
console.log(variable1) // outputs 12
logical AND operator assignment expression (||=)
This also applies to two variables/operands or javascript expressions.
if the first variable returns falsely
values, then the second variable is assigned to the first variable
let variable1 = undefined;
let variable2 = 44;
variable1 ||= variable2;
console.log(variable1) // outputs 44
As you see variable1 is falsely valued, falsely values are undefined, null, zero
let variable1 = undefined;
let variable2 = 12;
if(!variable1){
variable1 = variable2;
}
console.log(variable1) // outputs 12
logical Double question operator assignment expression (??=)
This also applies to two variables or operands in JavaScript.
if the first variable/operand is null
or undefined
, Then the second variable is assigned with the first variable
let variable1 = undefined;
let variable2 = 44;
variable1 ??= variable2;
console.log(variable1) // outputs 44
variable1 is undefined, which means variable2 is assigned with variable1
The above code is equivalent to
let variable1 = undefined;
let variable2 = 44;
if((variable1 ==null)||(variable2=undefined)){
variable1=variable2;
}
console.log(variable1) // outputs 44
Notes:
- Logical operators assignment expressions are applied to variable/operand/JavaScript expression
- Advantage of this is the shorter syntax
- Syntax confusion initially but easy to understand