Surely similar Bug we must have met

This is because we are trying to fetch data from undefined or NULL.

Solving this problem is actually quite simple, if we have the following objects:

const a = {
  b: {
    c: 1}}Copy the code

Suppose we now need to fetch A.B.C, but it’s not clear if they all exist, the code would look like this:

if (a && a.b) {
  const c = a.b.c
}
Copy the code

In fact, this kind of code is very frequent in the project, if the value hierarchy is too deep, the code will also be ugly, so can we solve this elegantly?

There must be a solution, which is to use the new syntax optional chain.

The syntax is not yet available, but you can use it by installing the Babel plugin.

npm install --save-dev @babel/plugin-proposal-optional-chaining
Copy the code

After installation, modify the Babel configuration file.

{
   "plugins": ["@babel/plugin-syntax-optional-chaining"]}Copy the code

We can then use the optional chain to transform the above code into something like this:

constc = a? .b? .cCopy the code

Babel compiles the code like this:

const c = a === null || a === null ? undefined : a.b === null || a.b === undefined ? undefined : a.b.c
Copy the code

While the compiled code looks a bit verbose, it is elegant and simple to write nullates.

However, the optional chain can be cratered in some scenarios, such as:

const a = {
  b: {
    c: false}}Copy the code

Let’s say we want to set the default value true for c in the value A.B.C

// true
constc = a? .b? .c ||true
Copy the code

However, in this scenario, there is a Bug where the expected value is false and the result is true.

It’s easy to solve this problem by introducing a new syntax double question mark. The role of the syntax and | | is similar, but only when the value is null or undefined will use the default values.

// false
constc = a? .b? .c ??true
Copy the code

The double question mark is also not released, but it can be solved by using the Babel plugin. The installation details are not detailed here.

That’s the content of this article. As an aside, I feel that the JS code will be occupied by various question marks in the future.

The last

Although the topic looks simple, but the content of the investigation is still various, of course, most want to say or fuckJS.

Feel the content is helpful can pay attention to my public number “front-end really fun”, regularly share the following theme content:

  • Front-end small knowledge, cold knowledge
  • The principle of content
  • Improve work efficiency
  • Personal growth