In ECMAScript 2021 (ES12), JavaScript introduced the new logical assignment operator&&=
respond in singing??=
. These operators combine logical operators with assignment operators to provide a more concise and intuitive way of assigning values.
Although it has been into the standard for a long time, but I have seen less in the actual development, today we come together to learn.
logical and assignment operators&&=
&&=
How it works
&&=
operator is the logical and operator (&&
) and the assignment operator (=
) of the combination. It works:Assign the right-hand side value to the left-hand side variable only if the left-hand side variable is true (truthy). The traditional way of writing requires the use ofif
statements or logical operators.&&=
provides a more concise approach.
A comparison of traditional writing styles:
// Use if statements
if (x) {
x = y;
}
// Use the logical and operators
x = x && y;
// Use of the `&&=` operator (ES2021)
x &&= y;
The concepts of true and false values
In JavaScript, the following values are consideredFalse values (falsy):
false
0
-
''
(empty string) null
undefined
NaN
All other values are treated asTruth (truthy)。
Example Analysis
Example 1: User Login Status
let isLoggedIn = true;
isLoggedIn &&= getUserData(); // if already logged in, get user data
function getUserData() {
return { name: 'ConardLi', age: 17 };
}
// Result: isLoggedIn becomes { name: 'ConardLi', age: 17 }
Example 2: Inventory Update
let stock = 17;
function sell(quantity) {
stock >= quantity &&= stock - quantity;
}
sell(5); // stock is 5
sell(17); // stock stays at 5 because 5 >= 17 is false
In the above example, thesell
The function reduces inventory only when there is enough inventory to prevent a negative inventory situation.
application scenario
(1) Conditional Update Attributes
let config = {
debugMode: true,
logLevel: null
};
// Set logLevel only if debugMode is true.
&&= ( = 'verbose');
// Result: 'verbose'
(2) Chain judgment
let user = {
isActive: true,
hasMembership: true
};
// Discounts are only given if the user is active and has a membership
&&= &&= applyDiscount();
function applyDiscount() {
return 'Discounts applied';
}
// Result: changes to 'Discount applied'
Null Merge Assignment Operator??=
??=
How it works
??=
operator combines the null merge operator (??
) and the assignment operator (=
). It works:Only if the left-hand side variable isnull
maybeundefined
The right-hand side value is assigned to the left-hand side variable only when the. This helps to provide default values when variables are not initialized.
A comparison of traditional writing styles:
// Use if statements
if ( === null || === undefined) {
= 3000;
}
// Use the null merge operator
= ?? 3000;
// Use the `? =` operator (ES2021)
??= 3000;
Comparison with other assignment methods
Question:
-
logical or
||
: would0
、''
、false
The case in which legal values such as the default value are considered to need to be assigned may lead to unintended results.
let delay = 0;
delay = delay || 1000; // delay was misassigned to 1000
Solution:
-
??=
: Only if the variable isnull
maybeundefined
The above problem is avoided by assigning values only when they are assigned.
let delay = 0;
delay ?? = 1000; // delay held at 0
Use the ternary operator:
= ( !== null && !== undefined) ? : 'Anonymous';
Question: The code is more lengthy and less readable.
utilization??=
:
??= 'Anonymous';
Advantage: Succinct and clear, only when the variable isnull
maybeundefined
The value is assigned only when the value is assigned and does not affect other dummy values.
application scenario
??=
operator is well suited to set default values for variables that may be undefined and do not interfere with valid dummy values.
Example:
let score = 0;
score ?? = 100; // Keep it at 0
let tag = '';
tag ?? = 'default'; // keep as ''
let active = false;
active ?? = true; // remain false
Configure the default parameters:
function initializeSettings(settings) {
??= 'light';
??= true;
??= 300;
return settings;
}
ultimate
JavaScript&&=
cap (a poem)??=
operator provides us with a more concise and precise way of assigning values:
-
&&=
Operator: Assigns only when the left-hand side variable is true, suitable for scenarios where you need to update a variable based on a true value condition while maintaining a false value. -
??=
Operator: Only in the case where the left-hand side variable isnull
maybeundefined
It is suitable for setting default values for undefined or null-valued variables.