As ECMAScript evolves, there will be many new features, such as destruction, arrows, and modules, that will dramatically change the way JavaScript is written. Some people may like it, some may not like it, but like every new feature, we’ll eventually get used to it. The new version of ECMAScript introduces three new logical assignment operators: the air AND AND OR operators. These operators were designed to make our code cleaner AND cleaner. Here are some elegant JavaScript operator tips.

Optional link operator [?.]

The Optional Chaining Operator is in phase 4 of the ES2020 proposal and should therefore be added to the specification. It changes the way properties inside objects are accessed, especially those that are deeply nested. It is also available as a feature in TypeScript 3.7+.

Most front-end developers will encounter null and undefined attributes. The dynamic nature of the JS language makes it impossible not to encounter them. Especially when dealing with nested objects, the following code is common:

if (data && data.children && data.children[0] && data.children[0].title) {
    // I have a title!
}


Copy the code

The code above is for the API response, and I have to parse the JSON to make sure the name exists. However, when objects have optional properties or dynamic mappings of some configuration objects with certain values, you may encounter a similar situation and need to check many boundary conditions.

At this point, if we use the optional link operator, everything becomes much easier. It allows us to examine nested properties without having to explicitly search the ladder diagram. All we have to do is use “?” To check the operator following the null-valued attribute. We can use this operator as many times as we like in the expression, and it will return as soon as possible if no items are defined.

For static attributes:

object? .propertyCopy the code

For dynamic properties change it to:

object? .[expression]Copy the code

The above code can be simplified as:

lettitle = data? .children? .0]? .title;Copy the code

Then, if we have:


let data;
console.log(data? .children? .0]? .title)// undefined

data  = {children: [{title:'codercao'}}]console.log(data? .children? .0]? .title)// codercao
Copy the code

Is it easier to write this way? Since the operator terminates once it is null, it can also be used to call methods conditionally or apply conditional logic


const conditionalProperty = null;
let index = 0;

console.log(conditionalProperty? .[index++]);// undefined
console.log(index);  / / 0
Copy the code

For method calls you can write this

object.runsOnlyIfMethodExists?.()
Copy the code

Uncaught TypeError: parent.getTitle is not a function error, parent.gettitle? .() terminates and is not executed

let parent = {
    name: "parent".friends: ["p1"."p2"."p3"].getName: function() {
      console.log(this.name) } }; parent.getName? . ()// parentparent.getTitle? . ()// Will not be executed
  
Copy the code

Use with invalid merge

Provides a way to handle undefined or default values for null values and expressions. We can use?? Operator that provides default values for expressions

console.log(undefined ?? 'codercao'); // codercao
Copy the code

Therefore, if the attribute does not exist, the invalid merge operator can be used with the optional link operator to provide a default value.

lettitle = data? .children? .0]? .title ??'codercao';
console.log(title); // codercao
Copy the code

Two, logical empty allocation (?? =)

expr1 ?? = expr2Copy the code

The logical nullish operator assigns values to exPR1 only when nullish values are null or undefined.

x ?? = yCopy the code

May look equivalent to:

x = x ?? y;
Copy the code

But that’s not the case! There are subtle differences.

Empty merge operator (??) Operate from left to right, if x is not nullish then the expression in is not executed. Therefore, if x is not null or undefined, the expression y is never evaluated. If y were a function, it would not be called at all. Therefore, this logical assignment operator is equivalent to

x ?? (x = y);
Copy the code

Three, logic or distribution (| | =)

This logical assignment operator assigns only if the expression on the left is falsy (imaginary). Falsy is different from null because Falsy can be any kind of value: undefined, null, empty string (double quote “”, single quote “, backquote “), NaN, 0. Document. all in Internet Explorer is also one.

grammar

x ||= y
Copy the code

Is equivalent to

x || (x = y)
Copy the code

This is useful in cases where we want to preserve the existing value (if none exists), otherwise we want to assign a default value to it. For example, if there is no data in the search request, we want to set the internal HTML of the element to the default value. Otherwise, we display the existing list. This way, we avoid unnecessary updates and any side effects such as parsing, re-rendering, loss of focus, etc. We can simply use this operator to update HTML with JavaScript:

document.getElementById('search').innerHTML ||= '<i>No posts found matching this search.</i>'
Copy the code

Iv. Logic and Distribution (&& =)

As you might have guessed, this logical assignment operator only assigns if the left side is true. Therefore:

x &&= y
Copy the code

Is equivalent to

x && (x = y)
Copy the code
The last

This article shares a few elegant JavaScript operator tips, focusing on the use of the optional link operator, which makes it easy to access nested properties without having to write a lot of code in our example. But Internet Explorer doesn’t support it, so if you need to support that version or an older browser, you may need to add the Babel plug-in. For Node.js, you need to upgrade to the Node 14 LTS version for this, since 12.x does not support this version.

If you have some elegant JavaScript operator skills, please share them in the comments section