background

Recently, I started to see some new features after ES6 that are really easier to use

In particular, recently there was an item that had to be passed an index in the method but in the case of non-empty validation if the index that was passed in was 0 it would be judged as false and that was a real headache

Redundant judgments not only make code less readable but also less concise

But with the optional chain operator, emmmmm is too fragrant to avoid && and redundant non-null checks

So I decided to start writing some ES6, ES7… New features later

Optional chain operator

I met

Here I quote an explanation from the MDN

The optional chain operator (? .) allows the value of properties deep in the chain of connected objects to be read without explicitly verifying that each reference in the chain is valid. ? The. Operator functions like the.chain operator, except that it does not cause an error if the reference is nullish (null or undefined), and the expression short-circuited to the return value is undefined. When used with a function call, undefined is returned if the given function does not exist.

Maybe you’re still?????

Don’t worry, let’s do an example

const adventurer = {
  name: 'link'.weapon: {
    name: 'Master Sword'}};constweaponName = adventurer.weapon? .name;console.log(weaponName);
// Expected output: Master sword

console.log(adventurer.savePrincess? . ());// expected output: undefined

constshieldName = adventurer.shield? .name;console.log(shieldName);
// expected output: undefined
Copy the code

The above example adventurer. Weapon? .name

We are trying to find the name attribute for the Weapon attribute under the Adventurer object

The Adventurer object has a weapon attribute so returning we can pull out our master sword

And then the adventurer. SavePrincess? . ()

< p style = “margin: 0px; margin: 0px; margin: 0px; Return undefined if it does not exist

Finally, the adventurer. Shields? .name

Similarly, we find that there is no shield property under the Adventurer object, so return undefined directly

Okay, so now we have a general idea of what an optional chain is

Now let’s look at the optional chain. What do we need to pay attention to

Pay attention to the point

Optional chains cannot be used for assignment

letobject = {}; object? .property =1; // Uncaught SyntaxError: Invalid left-hand side in assignment
Copy the code

Short circuit calculation

When using optional chains in an expression, the expression will not be evaluated if the left operand is null or undefined, for example:

let potentiallyNullObj = null;
let x = 0;
letprop = potentiallyNullObj? .[x++];console.log(x); // X will not be incremented and will still print 0
Copy the code

Finally, let me give you an example from your own development

Let’s say we have a method setStudentResult(action) that takes an object action

In order for our code to be robust we have to do a non-null check of the parameters inside of the method and obviously this is not going to work


const list = {};

/ * * *@param {*} action* /
function setStudent (action) {
  list[action.index] = action.student;
}
Copy the code

If we call setStudent() directly obviously the whole program will crash

So in the old days we could have changed the method like this

// The include function accepts the action argument and has the required content in the argument
function setStudent(action) {
  if (action) {
    if(action.index && action.student) { list[action.index] = action.student; }}}Copy the code

But using the optional chain operator we can define the method as follows

function setStudent (action) {
  if(action? .index && action? .student) { list[action.index] = action.student; }}Copy the code

You can see that the optional chain operator is superior in both readability and brevity

Null merge operator

Still quote a paragraph on MDN explanation

Null merge operator (??) Is a logical operator that returns the right-hand operand if the left-hand operand is null or undefined, and the left operand otherwise.

Compare the | |

We know that | | the Boolean or operator Also has similar function

In the | | the left operand is false value Returns the right The operand

The false values in JS are

  • 0

  • ‘ ‘

  • NaN

  • null

  • undefined

So imagine a scene We are a function of parameters using | | operators to determine whether the user input

function addNum(a,b) {
  var a = a || 0
  var b = b || 0
  return a + b 
}
Copy the code

The above code we use | | operators to judge the legitimacy of the user input from the user

But then we can’t rule out the 0 case

If the user is entered but 0 0 remains a false value So will return | | operator is on the right operand

That’s not what we expected

And???? The null merge operator just checks for null and undefined

Pay attention to the point

Short circuit calculation

Similar to the OR AND AND logical operators, the right expression is not evaluated when the left expression is not null OR undefined

var a = 1;
undefined ?? a++;
console.log(a); / / 1

var b = 1;
true ?? b++;
console.log(b); / / 2
Copy the code

Cannot be shared with the AND OR OR operators

null || undefined ?? "foo"; / / throw SyntaxError
true || undefined ?? "foo"; / / throw SyntaxError
Copy the code

Used with the optional chain operator

Both operators are for both undefined and null values

So we can combine these two operators

let customer = {
  name: "chou".details: { age: 100}};letcustomerCity = customer? .city ??"Breath of the Wilderness.";
console.log(customerCity); // Breath of the Wilderness
Copy the code