Three new features to look forward to JavaScript!

Let's look at some useful JavaScript in upcoming features. You will see their grammar, links, and when they understand progress, we will write a small test suite to demonstrate how to get started with these proposals!

How JavaScript is iterative update

If you are already familiar with the Ecma TC39 how the Commission decided to deal with change and the JavaScript language, please feel free to skip this section.

For the rest of us how the JavaScript programming language for the development of curious, I want a quick overview of the process.

JavaScript is called ECMAScript implementation language standard, which is used to create all standardized languages to achieve , because it was developed from the early Web browser.

There have been eight versions of the ECMAScript standard , there are seven versions (fourth edition abandoned).

Each JavaScript engine start implementing the specified changes after each release. This chart table will show that not every engine implements each function, and some engines need to achieve these functions than other engines longer. While this may not seem like the best, but I believe it is better than no standard!

Suggest

Each ECMAScript versions over the course of the audit proposal. If the proposal is considered useful and backward compatibility will be included in the next version.

There are five stages of the proposal, in an overview of this document . Each proposal is originally proposed "strawman" or Stage 0 . At this level, they are either not yet been submitted to the Technical Committee, or have not been rejected, but still not up to standard into the next phase.

Proposal shown below do not belong to the zeroth stage.

As a personal recommendation, I want to encourage readers to avoid the use of phase 0 proposals in a production application, until they are in a precarious stage. The purpose of this recommendation is to avoid the problem only occurs when the proposal was abandoned or radically changed.

Test Suite

It describes the programming function normally shows snippet from the context, or use them to build applications. Because I am a TDD loyal fans, I believe that a better way to understand the role of the function is to test it.

We will use Jim Newkirk create learning test to achieve this goal _._, we write the test will not assertions about our own code, but about the programming language itself. When learning a third-party API, or any other language features, this same concept is very useful.

Transpilers

If you are familiar with the converter, please feel free to skip this section.

Some people may be wondering how we will use the language features not yet implemented!

JavaScript is an evolving language, with some of it will be compiled into JavaScript JavaScript- converter . It may not sound very helpful on the surface, but I assure you!

It allows us to write the latest version of JavaScript - even including zero stage proposal - and still be able to execute it, such as Web browsers and Node.js. in today's environment when running it by changing our code to older versions of JavaScript write to achieve this purpose .

Babel is one of the most popular JavaScript transponders. We will use it immediately.

step

You need to install Node.js and NPM .

To do this, you can run the following command in the new directory:

npm init -f && npm i [email protected] @babel/[email protected] @babel/[email protected] @babel/[email protected] @babel/[email protected] @babel/[email protected] @babel/[email protected] --save-dev

Then, you need to add the following to the package.json file:

"scripts": {  "test": "ava"},"ava": {      "require": [          "@babel/register",    "@babel/polyfill"     ]  }

Finally, create a .babelrc file:

{    "presets": [        ["@babel/preset-env", {            "targets": {                "node": "current"            }        }],        "@babel/preset-stage-0"    ],    "plugins": [        "@babel/plugin-transform-runtime"  ]}

Now you're ready to start writing some tests up!

1. Optional link

In JavaScript, we have been using Objects. Sometimes these objects is not the exact shape of our expectations. Below you will find a man-made data object example - may be retrieved from a database or API calls to.

const data = {  user: {    address: {      street: 'Pennsylvania Avenue',    },   },};

Alas, it seems that the user does not complete the registration:

const data = {  user: {},};

Suppose, when I try to access the application dashboard street, I get the following error:

console.log(data.user.address.street);
// Uncaught TypeError: Cannot read property 'street' of undefined

To avoid this, we must now access the "street" attribute as follows:

const street = data && data.user && data.user.address && data.user.address.street;console.log(street);
// undefined

In my opinion, this approach is:

  1. Unsightly
  2. Onerous
  3. Long-winded

Here is a link to an optional place. You can use it like this:

console.log(data.user?.address?.street);
// undefined

It is easier, right? Now we have seen the usefulness of this feature, we can continue in-depth study.

So we have to write a test!

Now we see optional link to keep the dot notation previous function. Next, let's add a test for unpleasant path.

The following are optional link for how to access an array of attributes:

Sometimes we do not know whether the function is realized in Object.

A common example is when you use a Web browser. Some older browsers may not have some features. Fortunately, we can use an optional link to detect whether the function has been achieved!

If the chain is not complete, the expression will not be executed. Behind the scenes, the expression roughly into:

value == null ? value[some expression here]: undefined;

Nothing after an optional chain operator? If the value is undefined or null, it will be executed. We can see the practical application of this rule in the following tests:

With it! Optional link reduces the import library for the if statement, lodash, etc. and use && linking needs.

Word of caution: You may notice this optional chain brought some minimal overhead. You check each level? Under certain conditions must be included in the logic of the hood. If excessive use, will result in loss of performance. When you receive or create objects, I recommend using it for some kind of object verification. This will limit demand for these checks, which limits the performance loss.

link

This is the proposal of the link . I will copy it at the bottom of this article, so you can see all proposals links in one place!

2. merger null

Merge: or to fuse together

Here are some common actions that we see in JavaScript:

  1. Check undefined or null
  2. Defaulting Values
  3. Ensure 0, false and an empty string is not the default.

You may have seen it like this:

value != null ? value : 'default value';

Or this:

value || 'default value'

The problem is that, for the implementation of the second, our third operating condition is not satisfied. In this case, the number zero, the Boolean value false and empty strings are treated as false. This is what we have to clear the check for null and undefined reasons.

value != null

This is:

value !== null && value !== undefined

That's where the new proposal (invalid merger) of. Now we can do this:

value ?? 'default value';

This can protect those we do not accidentally default false value, but still will not ternary and! Capture null and undefined case = null check.

Now we see the grammar, we can write a simple test to verify how it works.

You can see it in testing the use of null, undefined and defaults void 0 (calculated result is undefined). It does not default false value, such as 0, 'and false. In this view GitHub.

3. The pipeline operator

In functional programming, we have a term " combination ", which is a multiple function calls are linked behavior. Receiving one output of the previous function as a function of its input. The following is an example of our discussion in pure JavaScript:

function doubleSay (str) {  return str + ", " + str;}
function capitalize (str) {  return str[0].toUpperCase() + str.substring(1);}
function exclaim (str) {  return str + '!';}
let result = exclaim(capitalize(doubleSay("hello")));result //=> "Hello, hello!"

This series is so common that a combination of functions found in most libraries, as lodash and Ramda .

Using the new pipeline operators, you can skip the third-party libraries shown above press written as follows:

let result = "hello"  |> doubleSay  |> capitalize  |> exclaim;result //=> "Hello, hello!"

The purpose is to make the chain _ _ more readable. It will also work well in the next part of the application, or it can now achieve something like this:

let result = 1  |> (_ => Math.max(0, _));result //=> 1
let result = -5  |> (_ => Math.max(0, _));result //=> 0

Now we see the grammar, we can start writing the test!

One thing you may notice is that once the pipeline to add asynchronous function, you must wait for the value. This is because the value has been committed. There are some proposed changes support |> wait asyncFunction, but has not been implemented or decision.

Well, since you've seen the practical application of these recommendations, I hope you try these suggestions!

Learning tests complete code here can be found .

The following are links to all four proposals:

tc39/proposal-optional-chaining _Contribute to proposal-optional-chaining development by creating an account on GitHub._github.com[](https://github.com/TC39/propo...

tc39/proposal-nullish-coalescing _proposal-nullish-coalescing - Nullish coalescing proposal x ?? y_github.com[](https://github.com/tc39/propo...

tc39/proposal-partial-application _proposal-partial-application - Proposal to add partial application to ECMAScript_github.com[](https://github.com/tc39/propo...

tc39/proposal-pipeline-operator _proposal-pipeline-operator - A proposal for adding the simple-but-useful pipeline operator to JavaScript._github.com[](https://github.com/tc39/propo...

Guess you like

Origin www.cnblogs.com/baimeishaoxia/p/11888424.html