4 powerful JavaScript operators

Keywords: Javascript

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 // => 5
3 ?? 5 // => 3

  

When setting default values for variables, logic or operators were commonly used, for example,

var prevMoney = 1
var currMoney = 0
var noAccount = null
var futureMoney = -1
function moneyAmount(money) {
return money || `Account not opened`
}
console.log(moneyAmount(prevMoney)) // => 1
console.log(moneyAmount(currMoney)) // =>Account not opened
console.log(moneyAmount(noAccount)) // =>Account 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 = 0
var noAccount = null
function moneyAmount(money) {
  return money ?? `Account not opened`
}
moneyAmount(currMoney) // => 0
moneyAmount(noAccount) // =>` account 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 = null
var y = 5
console.log(x ??= y) // => 5
console.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 this Front end training The difference between the operator and the default parameter (Note: the default parameter is a new syntax introduced in ES6, and a default value is set only when the function parameter is undefined):

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. 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; // Only when newPlans is undefined can it be overwritten
    console.log("Scheduled")
  }
  return newPlans
}
// 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
// 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 tuesday.location that currently has no nested properties. 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 = 0
var transportion = (budget > 0) ? 'train' : 'walk'
console.log(transportion) // =>'walk'

We can even use it to realize the behavior of null assignment:

var x = 6
var x = (x !== null || x !== undefined) ? x : 3
console.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) // => 8
nullishAssignment(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;
}

  

conclusion
Now that we have learned how to use these operators, we have more knowledge about these operators here.

(Note: the first three operators in the text are new features of ES2020. Do not use them directly in the production environment. You can use webpack+babel to escape to solve the browser compatibility problem.)

Posted by growler123 on Mon, 06 Dec 2021 23:42:13 -0800