Did you spend an afternoon reading Mozilla documents? If so, you will find a lot of JS information on the Internet, which makes it easy for us to ignore the more basic JS operators.
These operators are uncommon but powerful! It looks very similar in grammar, but its function is different. You must read it carefully.
1. ?? Non air operator
In JS,?? Operators are called non airlift operators. If the first parameter is not null/undefined, the first parameter will be returned, otherwise the second parameter will be returned. For example,
null ?? 5 // => 53 ?? 5 // => 3
When setting default values for variables, logic or operators were commonly used, for example,
var prevMoney = 1var currMoney = 0var noAccount = nullvar futureMoney = -1function moneyAmount(money) {return money || `Account not opened`}console.log(moneyAmount(prevMoney)) // => 1console. Log (moneyamount (currmoney)) / / = > the account has not opened console Log (moneyamount (noaccount)) / / = > the account has not opened console log(moneyAmount(futureMoney)) // => -1
Above, we created the function moneyAmount, which returns the current user balance. We use the | operator to identify users without accounts. However, what does this mean when a user does not have an account? It is more accurate to treat no account as empty rather than 0, because bank accounts may not have (or negative) currency. In the above example, the | operator treats 0 as a false value and should not include the user's account with $0. Let's use?? Non null operators to solve this problem:
var currMoney = 0var noAccount = nullfunction moneyAmount(money) { return money ?? `Account not opened`}moneyAmount(currMoney) // =>0moneyamount (noaccount) / / = > ` the account is not opened`
To sum up?? Operator allows us to specify default values while ignoring error values such as 0 and empty strings.
2. ??= Null assignment operator
??= Also known as the null assignment operator, it is related to the non null operator above. Look at the connection between them:
var x = nullvar y = 5console.log(x ??= y) // => 5console.log(x = (x ?? y)) // => 5
This assignment operator assigns a value only if the value is null or undefined. The above example emphasizes that this operator is essentially a null assignment syntax sugar. Next, let's look at the difference between this operator and the default parameter:
function gameSettingsWithNullish(options) { options.gameSpeed ??= 1 options.gameDiff ??= 'easy' return options}function gameSettingsWithDefaultParams(gameSpeed=1, gameDiff='easy') { return {gameSpeed, gameDiff}}gameSettingsWithNullish({gameSpeed: null, gameDiff: null}) // => {gameSpeed: 1, gameDiff: 'easy'}gameSettingsWithDefaultParams(undefined, null) // => {gameSpeed: null, gameDiff: null}
There is a notable difference in the way the above functions handle null values. Front end training The default parameter will overwrite the default value with an empty parameter, and the empty assignment operator will not. Neither the default parameter nor the null assignment overrides the undefined value.
3. ?. Chain judgment operator
Chain judgment operator Allows developers to read property values deeply nested in the object chain without having to validate each reference. When the reference is empty, the expression stops evaluating and returns undefined. For example:
var travelPlans = { destination: 'DC', monday: { location: 'National Mall', budget: 200 }}console.log(travelPlans.tuesday?.location) // => undefined
Now, combine what we just learned and add tuesday to our travel plan!
function addPlansWhenUndefined(plans, location, budget) { if (plans.tuesday?.location == undefined) { var newPlans = { plans, tuesday: { location: location ?? "park", budget: budget ?? 200 }, } } else { newPlans ??= plans; // The console is overwritten only when newPlans is undefined Log ("scheduled plans")} return newPlans} / / translator's note: the initial value of the object travelPlans comes from the above example var newPlans = addPlansWhenUndefined(travelPlans, "Ford Theater", null) console Log (newPlans) / / = > {plans: / / {destination: 'DC', / / Monday: {location: 'national shopping center', budget: 200}}, / / Tuesday: {location: 'Ford Theater', budget: 200}} newPlans = addplanswhenundefined (newPlans, null, null) / / logs = > scheduled plans / / returns = > newPlans object
The above example contains all the operators we have learned so far. Now we have created a function that adds the plan to the object that currently has no nested properties, Tuesday Location. We also use non null operators to provide default values. This function will incorrectly accept a value like '0' as a valid argument. This means that the} budget can be set to zero without any errors.
4. ?: Ternary operator
?: Also called conditional operator, it accepts three operands: condition? Expression to execute when condition is true: expression to execute when condition is false. Actual effect:
function checkCharge(charge) { return (charge > 0) ? 'available' : 'Recharge required' }console.log(checkCharge(20)) // =>Available console Log (checkcharge (0)) / / = > recharge required
If you have written JS, you may have seen ternary operators. However, do you know that ternary operators can be used for variable assignment?
var budget = 0var transportion = (budget > 0) ? 'train' : 'walk' console.log(transportion) // =>'walk'
We can even use it to realize the behavior of null assignment:
var x = 6var x = (x !== null || x !== undefined) ? x : 3console.log(x) // => 6
Let's summarize this operation by creating a function:
function nullishAssignment(x,y) { return (x == null || x == undefined) ? y : x }nullishAssignment(null, 8) // => 8nullishAssignment(4, 8) // => 4
Before we finish, let's reconstruct the function in the previous example using the ternary operator:
function addPlansWhenUndefined(plans, location, budget) { var newPlans = plans.tuesday?.location === undefined ? { plans, tuesday: { location: location ?? "park", budget: budget ?? 200 }, } : console.log("Scheduled"); newPlans ??= plans; return newPlans;}