Have you ever spent an afternoon reading Mozilla documentation? If you do, you know that there is a lot of information about JavaScript on the web. This makes it easy to ignore the more unusual JavaScript operators. However, just because these operators aren’t common doesn’t mean they aren’t powerful! They look similar grammatically, but be sure to read them because they work in different ways.

Let’s get started!

1. ?? The operator

In JavaScript, the??The operator is callednullishOperator (null/undefined). If it is not null/undefined, this operator returns the first argument, otherwise, it returns the second argument.

null ?? 5 // => 5
3 ?? 5 // => 3
Copy the code

When assigning default values to variables, JavaScript developers have traditionally relied on the logical OR operator, as shown below.

var prevMoney = 1 var currMoney = 0 var noAccount = null var futureMoney = -1 function moneyAmount(money) { return money  || `You currently do not own an account in the bank` } console.log(moneyAmount(prevMoney)) // => 1 console.log(moneyAmount(currMoney)) // => `You currently do not own an account in the bank` console.log(moneyAmount(noAccount)) // => `You currently do not own an account in the bank` console.log(moneyAmount(futureMoney))// => -1Copy the code

Above we created a function, moneyAmount, that returns the user’s current balance. We use the | | to identify without the users account. When money is 0 or null it returns that there is no account in the current bank, when in fact the account could be 0. In the example above, the | | operator will 0 as the false value, so as not to identify our users to have zero dollars account. Next, let’s use?? Operator to solve the problem.

var currMoney = 0
var noAccount = null

function moneyAmount(money) {
  return money ?? `You currently do not own an account in the bank`
}
 moneyAmount(currMoney) // => 0
 moneyAmount(noAccount) // => `You currently do not own an account in the bank`
Copy the code

To sum up,?? Operators allow us to assign default values while recognizing 0 and ignoring spurious values such as null.

2. ?? = operator.

?? = also known as the logical NULL /undefined assignment operator, closely related to what we learned earlier. Let’s see how they fit together.

var x = null var y = 5 console.log(x ?? = y) // => 5 console.log(x = (x ?? y)) // => 5Copy the code

If the current value is null/undefined, this?? The = operator assigns a new value. The above example underscores that this operator is essentially a syntactic sugar for null/undefined assignments. Next, let’s look at how this operator differs from the default argument.

function gameSettingsWithNullish(options) { options.gameSpeed ?? = 1 options.gameDiff ?? = 'easy' return options } function gameSettingsWithDefaultParams(gameSpeed=1, gameDiff='easy') { return {gameSpeed, gameDiff} } gameSettingsWithNullish({gameSpeed: 2, gameDiff: 'busy'}) // => {gameSpeed: 2, gameDiff: "busy"} gameSettingsWithNullish({gameSpeed:'', gameDiff: undefined})// => {gameSpeed: "", gameDiff: "easy"} gameSettingsWithNullish({gameSpeed: null, gameDiff: null}) // => { gameSpeed: 1, gameDiff: 'easy' } gameSettingsWithDefaultParams(null, null) // => { gameSpeed: null, gameDiff: null } gameSettingsWithDefaultParams('', undefined) // => {gameSpeed: "", gameDiff: "easy"}Copy the code

There is one notable difference in the way the above functions handle null values. Default arguments will be overwritten by null. The = operator does not. Default arguments and null/undefined assignments do not override undefined values. To read more

3. ? The operator

Optional link operators? . Allows developers to read property values that are deeply nested in a chain of objects without explicitly validating every reference along the way. When the reference is null, the expression stops evaluating and returns undefined. Let’s look at an example.

var travelPlans = { destination: 'DC', monday: { location: 'National Mall', budget: 200 } }; const tuesdayPlans = travelPlans.tuesday? .location; console.log(tuesdayPlans) // => undefinedCopy the code

Now, let’s put everything we’ve learned so far together and add Tuesday to our new travel schedule

function addPlansWhenUndefined(plans, location, budget) {
  if (plans.tuesday?.location === undefined) {
    var newPlans = {
      plans,
      tuesday: { location: location ?? "Park", budget: budget ?? 200 },
    };
  } else {
    newPlans ??= plans; //will only override if newPlans is undefined
    console.log("Plans have already been added!");
  }
  return newPlans;
}

var newPlans = addPlansWhenUndefined(travelPlans, "Ford Theatre", null);
console.log(newPlans) // => { plans:
                  //{ destination: 'DC',
                  // monday: { location: 'National Mall', budget: 200 } },
                  // tuesday: { location: 'Ford Theatre', budget: 200 } }

newPlans = addPlansWhenUndefined(newPlans, null, null) // logs => Plans have already been added!
                                                      // returns => newPlans object
Copy the code

We have now created a function that adds the plan to Tuesday. Location, an object that currently has no nested properties. We also use?? Operator to provide default values. This function mistakenly accepts a value like “0” as a valid argument. This means that our budget can be set to zero without any errors.

4. ? The operator

Ternary operators? Takes three operands: a condition, an expression executed if the condition is true, and an expression executed if the condition is false. Let’s see it in action.

function checkCharge(charge) {
return (charge > 0) ? 'Ready for use' : 'Needs to charge'
}

console.log(checkCharge(20)) // => 'Ready for use'
console.log(checkCharge(0)) // => 'Needs to charge'
Copy the code

If you know anything about JavaScript, you’ve probably seen ternary operators before. But did you know that ternary operators can be used for variable assignment?

var budget = 0
var transportion = (budget > 0) ? 'Train' : 'Walking'
console.log(transportion) // => 'Walking'
Copy the code

We can even use it to replicate the behavior of null/undefined assignments.

var x = 6 var x = (x ! == null || x ! == undefined) ? x : 3 console.log(x) // => 6Copy the code

Now let’s generalize this behavior by creating a function!

function nullishAssignment(x,y) { return (x == null || x == undefined) ? Y: x} var x = nullishAssignment(null, 8) // => 8 var y => 8Copy the code

Before we finish, let’s use the ternary operator to reconstruct the function from the previous example.

function addPlansWhenUndefined(plans, location, budget) { var newPlans = plans.tuesday? .location === undefined ? {... plans, tuesday: { location: location ?? "Park", budget: budget ?? 200 }, } : console.log("Plans have already been added!" ); newPlans ?? = plans; return newPlans; }Copy the code

conclusion


Conclusion: congrats ✌ ️ ✌ ️ ✌ ️ ✌ ️ ✌ ️ ✌ ️ ✌ ️ ✌ ️ ✌ ️ ✌ ️ ✌ ️ ✌ ️ ✌ ️ ✌ ️ ✌ ️ ✌ ️ ✌ ️ ✌ ️ ✌ ️ ✌ ️ links: the original javascript. Plainenglish. IO / 4 – powerful -…