JavaScript ES6 Core Features at a glance

Source: Internet
Author: User

JavaScript has changed a lot in the last few years. Here are 12 new features you'll be able to use right away.

JavaScript history

The new language specification is called ECMAScript 6. Also known as ES6 or es2015+.

Since the birth of JavaScript in 1995, it has been developing slowly. New content is added every few years. In the 1997, ECMAScript became the norm for the JavaScript language implementation. It already has several versions, such as ES3, ES5, ES6 and so on.

As you can see, there are 10 and 6-year intervals between ES3,ES5 and ES6 respectively. The pattern of a major modification like ES6 is replaced by a new pattern that is progressively progressive each year.

Browser support

All modern browsers and environments have supported ES6.

Source: https://kangax.github.io/compat-table/es6/

Chrome,ms Edge,firefox,safari,node and many other environments have built-in support for most JavaScript ES6 features. So, you can start applying everything you've learned in this tutorial right away.

Let's start learning ECMAScript 6!

Core ES6 Features

You can test all of the following code snippets in the browser's console.

Don't take my word for it, but try to test every example of ES5 and ES6 in person. Let's get started, shall we??

Block-level scopes for variables

Using ES6, declare variables we can use VAR, or we can use let or const.

What are the disadvantages of Var?

The problem with Var is that the variable is leaking into other blocks of code, such as a for loop or an if code block.

For test (FASLE), you expect to return outer, but what you get is undefined.

Why?

The expression var x in line Fourth is also promoted, although the if code block is not executed.

var boost:

var is a function scope. is available throughout the function, even before declaring the statement.

Claims are promoted. So you can use a variable before the declaration.

Initialization is not promoted. If you use Var to declare a variable, always place it at the top.

After applying the claim elevation rule, we can make it easier to understand what's going on:

ECMAScript 2015 found a way to fix it:

Change Var to let and the code will run as expected. If the if code block is not called, the X variable is not promoted outside the code block.

Let lift and "staging dead Zone (temporal dead Zone)"

    • In ES6, let's raise the variable to the top of the code block (not the top of a function like ES5).

    • However, in a code block, referencing it before the variable declaration causes a referenceerror error.

    • Let is a block-level scope. You cannot refer to it before it is declared.

    • The Staging dead Zone (temporal dead zone) refers to the area from the beginning of the code block until the variable is declared.

Iife

Let's look at an example before explaining Iife. Take a look:

As you can see, private leaks out (blocks of code). You need to include it by using Iife (immediately-invoked function expression, immediately executing the formula):

If you take a look at jquery/loadsh or other open source projects, you will notice that they use iife to avoid polluting the global environment and only define such _,$ and jQuery in the global context.

At a glance on the ES6, we can use only blocks of code and let, and no longer need to use Iife.

Const

If you want a variable to remain constant (constants), you can also use Const.

In short: Using Let,const instead of Var

Use const for all references, and avoid using Var.

If you have to reassign the reference, replace the const with let.

Template literal

With the template literal, we don't have to do extra nesting stitching. Take a look:

Now you can use the anti-quote (') and string interpolation ${}:

Multi-line string

We no longer need to add + \ n to stitch strings:

On ES6, we can use the same anti-quote to solve this problem:

The result of the two pieces of code is exactly the same.

Deconstruction Assignment

The deconstruction of ES6 is not only practical but also concise. As shown in the following example:

Getting elements from an array

Equivalent to:

Exchange value

Equivalent to:

Deconstruction of multiple return values

In line 3rd, you can also return with an array like this (with some coding omitted):

On the other hand, callers need to consider the order in which the data is returned.

With ES6, callers simply select the data they need (line 6th):

Note: In line 3rd, we have used some of the other ES6 features. We will simplify {Left:left} to only {left}. It has become so concise compared to the ES5 version. Cool, not cool?

The deconstruction of parameter matching

Equal to (but more concise):

Depth matching

Equal to (but more concise):

This is also known as the deconstruction of objects.

As you can see, deconstruction is very practical and facilitates good coding style.

Best Practices:

    • Use an array to deconstruct to get the element or exchange value. It can avoid creating temporary references.

    • Instead of using an array to deconstruct multiple return values, use an object to deconstruct it.

Classes and objects

With ECMAScript 6, we are from the "constructor"?? Came to the "class"??。

In JavaScript, each object has a prototype object. All JavaScript objects inherit methods and properties from their prototype objects.

In ES5, in order to implement object-oriented programming (OOP), we use constructors to create objects, as follows:

There are some grammatical sugars in the ES6. By using keywords like class and constructor and reducing boilerplate code, we can do the same thing. In addition, speak () is clearer relative to Constructor.prototype.speak = function ():

As you can see, the two styles (ES5 and 6) produce the same results in the background and are consistent in usage.

Best Practices:

    • Always use class syntax and avoid direct manipulation of prototype directly. Why? Because it makes the code more concise and easy to understand.

    • Avoid using an empty constructor. If not specified, the class has a default constructor.

Inherited

Based on the previous Animal class. Let's extend it and define a Lion class.

In ES5, it has more to do with prototype inheritance.

I won't repeat all the details, but please note:

    • In line 3rd, we add parameters that explicitly call the Animal constructor.

    • 7–8, we assign the Lion prototype to the Animal prototype.

    • In line 11th, we call the Speak method of the parent class Animal.

In ES6, we have a new keyword extends and super

Although the code for ES6 and ES5 is consistent, the code for ES6 appears to be easier to read. A better one!

Best Practices:

Use the extends built-in method to implement inheritance.

Native Promises

From a callback to hell?? To promises

We have a function that receives a callback when done. We have to do it one after another two times. This is why we call Printaftertimeout the second time in the callback.

If you need a 3rd or 4th callback, it's likely to get messy in a very short time. Let's take a look at the wording we used promises:

As you can see, using promises we are able to do something after the function is complete. Nested functions are no longer required.

Arrow functions

ES6 did not remove the function expression, but a new one, called the arrow function.

In ES5, we have some questions about this:

You need to use a temporary this to reference inside the function or bind with bind. In ES6, you can use the arrow function.

For...of

From for to ForEach to For...of:

The for...of of ES6 can also be implemented iteratively.

Default parameters

Checks whether a variable is defined to reassign a value to the default parameters. Have you ever written a code like this before?

There may have been, this is a common pattern for checking whether a variable is assigned a value, otherwise a default value is assigned. However, here are some questions:

    • In line 8th, we pass in 0, 0 returns 0,-1.

    • In line 9th, we pass in false but return true.

If you pass in a Boolean value as the default parameter or set the value to 0, it does not work correctly. You know why? I'll tell you after I finish the ES6 example.

With ES6, you can now do better with less code!

Please note that line 5th and line 6th, we have the expected results. The ES5 example is not valid. First check whether it equals undefined, because false,null,undefined and 0 are false values, we can avoid these numbers,

When we check whether it is undefined, we get the desired result.

Remaining parameters

From parameters to remaining parameters and extended operators.

In ES5, it is cumbersome to get any number of parameters:

We can use the rest operator ... Do the same thing.

Expand operator

From the Apply () to the expand operator. We also use ... To solve:

Reminder: We use Apply () to convert an array to a list of parameters. For example, Math.max () works on a list of parameters, but if we have an array, we can use apply to make it work.

As we have seen earlier, we can use apply to pass an array as a parameter list:

In ES6, you can use the expand operator:

Similarly, from the concat array to the use of the expand operator:

In ES6, you can use the expand operator to flatten the nesting:

Summarize

JavaScript has undergone quite a number of changes. This article covers most of the core features that every JavaScript developer should know. Again, we've introduced some best practices that make your code more concise and easy to understand.

JavaScript ES6 Core Features at a glance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.