Why doesn’t Yu Stream use the optional chain operator in the Vue3 code base

How many times did you use the optional chain operator when writing code today, and suddenly remembered that someone mentioned a PR in the Vue3 code library last year? .replaced &&, but closed. At that time, I took a glance at the reason, but only said that it would be converted into complex code, and then stopped looking at it. Today, I suddenly wondered what kind of code it would be converted into. So I gave it a try.

What is an optional chain operator

Here is an explanation link for MDN [1]

The optional chain operator (? .) allows you to read the value of a property located deep in the chain of connected objects without explicitly validating that each reference in the chain is valid. ? The. Operator functions like the. Chain operator, except that it does not cause errors when references are nullish (null or undefined), and the short-circuit returns undefined. When used with a function call, returns undefined if the given function does not exist.

An example of MDN is as follows

// let nestedProp = obj.first &&obj.first. Second; // Let nestedProp = obj.first? .second;Copy the code

An extremely convenient syntax, no doubt.

Why not use the Vue3 code base

Let’s look at the PR link [2]. Modifications submitted by the author:

Reply from University of Utah

We purposely avoided using optional chains in the code base because we were aiming for ES2016 and TS would have converted it into something more verbose.

What is this more verbose content, I use TS to try the above example, after converting js results as follows

var _a;
let obj = {
    first: {
        second: 2022
    }
};
let nestedProp = (_a = obj.first) === null || _a === void 0 ? void 0 : _a.second;
Copy the code

Well, the readability is poor. One might wonder, isn’t optional chaining an ES6 syntax? Why was it turned this way?

Here is my understanding. In fact, ES6 is a different concept from ES5, and now there are new proposals for JavaScript every year. ES6 actually refers to ES2015 and later versions. Uvu is aiming for ES2016 for compatibility with older browsers, and the optional chain is ES2020 syntax, so it will be converted to the above.

Json (ES2020); tsconfig.json (ES2020)

let obj = { first: { second: 2022 } }; let nestedProp = obj.first? .second;Copy the code

Same as before conversion.

Reference links

[1] Link: *developer.mozilla.org/zh-CN/docs/…

[2] Link: github.com/vuejs/core/…