8
头图

In the development process of ECMAScript, there will be many functional updates, such as destruction, arrow functions, and modules. They greatly change the way JavaScript is written. Some people may like it, some people may not, but like every new feature, we will eventually Get used to them. The new version of ECMAScript introduces three new logical assignment operators: null operator, AND and OR operators. The appearance of these operators also hopes to make our code cleaner and concise. Here are a few elegant JavaScript operators. skills

1. Optional link operator [? .】

Optional Chaining Operator in the 4th stage of the ES2020 proposal, so it should be added to the specification. It changes the way to access the internal properties of the object, especially the deeply nested properties. It can also be used as a feature in TypeScript 3.7+.

I believe that most of the small partners who develop the front-end will encounter null and undefined attributes. The dynamic nature of JS language makes it impossible not to touch 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!
}

The above code is for API response, I have to parse JSON to make sure the name exists. However, when objects have optional attributes or certain configuration objects have dynamic mappings of certain values, similar situations may be encountered and many boundary conditions need to be checked.

At this time, if we use the optional link operator, everything becomes easier. It checks the nested properties for us without having to search the ladder diagram explicitly. All we have to do is use the "?" operator after the attribute to check for null values. We can use this operator as many times as we want in the expression, and if nothing is defined, it will return as soon as possible.

usage of 1608640813040b for the static attribute

object?.property

For dynamic attributes change it to:

object?.[expression] 

The above code can be simplified to:

let title = data?.children?.[0]?.title;

Then, if we have:


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

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

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


const conditionalProperty = null;
let index = 0;

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

For , you can write like this

object.runsOnlyIfMethodExists?.()

For example the following parent object, if we directly call parent.getTitle() , will be reported Uncaught TypeError: parent.getTitle is not a function error, parent.getTitle?.() will not terminate execution

let parent = {
    name: "parent",
    friends: ["p1", "p2", "p3"],
    getName: function() {
      console.log(this.name)
    }
  };
  
  parent.getName?.()   // parent
  parent.getTitle?.()  //不会执行
  

with invalid merge

Provides a way to handle undefined or provide default values for empty values and expressions. We can use the ?? operator to provide a default value for the expression

console.log(undefined ?? 'codercao'); // codercao

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

let title = data?.children?.[0]?.title ?? 'codercao';
console.log(title); // codercao

2. Logical empty allocation (?? =)

expr1 ??= expr2

The logical null operator assigns a value to expr1 only when it has a null value ( null or undefined ), the expression is:

x ??= y

May look equivalent to:

x = x ?? y;

this is not the truth! There are subtle differences.

The empty coalescing operator (??) operates from left to right, and if x is not empty, it is short-circuited. Therefore, if x is not null or undefined , the expression y will never be evaluated. Therefore, if y is a function, it will not be called at all. Therefore, this logical assignment operator is equivalent to

x ?? (x = y);

3. Logical OR Assignment (|| =)

This logical assignment operator only assigns values when the Falsy value is different from null, because falsy value can be any value: undefined, null, empty string (double quote "", single quote ``, back quote ``), NaN, 0. The document.all in IE browser can also be regarded as one.

grammar

x ||= y

Equivalent to

x || (x = y)

This is useful in situations where we want to keep the existing value (if it doesn't exist), otherwise we want to assign it a default value. For example, if there is no data in the search request, we want to set the internal HTML of the element as the default value. Otherwise, we want to display the existing list. In 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 the HTML using JavaScript:

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

Four, logic and distribution (&& =)

As you might have guessed, this logical assignment operator only assigns a value when the left side is true. therefore:

x &&= y

Equivalent to

x && (x = y)
At last

This time I will share a few elegant JavaScript operator skills, focusing on sharing the use of optional link operators, so that we can easily access nested attributes without writing a lot of code in our example. But IE does not support it, so if you need to support this version or older browsers, you may need to add the Babel plugin. For Node.js, you need to upgrade to Node 14 LTS version for this, because 12.x does not support this version.

If you also have an elegant and elegant JavaScript operator skills, please don't hesitate to communicate together in the comment area~


codercao
395 声望19 粉丝