ES6 is now used extensively in many projects. I also recently spent some time looking at Understanding Cript6 as a Chinese ebook. Some of the new features commonly used in real-world development are summarized here.

Block-level scope

Before ES6, JS had only one way to declare variables — variables declared using the var keyword. This way of declaring a variable is treated as if it were declared at the top of the function (or at the top of the global scope if the declaration is not in any function), regardless of where it is actually declared. This is called variable ascending (or reactive). ES6 introduces block-level scopes to make the life cycle of variables more manageable.

Block-level statement

Block-level declarations make declared variables inaccessible outside the scope of the specified block. Block-level scopes (also known as lexical scopes) are created when:

  1. Inside a function
  2. Inside a code block (enclosed by a pair of curly braces)

    Let the statement

    The let declaration limits the scope of the variable to the current code block. Since the LET declaration is not promoted to the top of the current code block, you need to manually place the let declaration at the top to make variables available within the entire code block. Such as:

    function getValue(condition) { if (condition) { let value = "blue"; // Other code return value; } else {// value cannot return null here; } // value is not available here}Copy the code

If an identifier is already defined within a code block, using the same identifier for let declarations within that code block will cause an error to be thrown. Such as:

var count = 30; let count = 40; // Syntax errorCopy the code

On the other hand, declaring a new variable with the same name using let in a nested scope does not throw an error, as demonstrated in the following code:

var count = 30; If (condition) {let count = 40; // Other code}Copy the code

Constant statement

In ES6 it is also possible to declare using const syntax. Variables declared with const are considered constant. Const is similar to let, but with an important difference that the value of a variable declared by const cannot be changed after it has been set. Because of this, all const variables need to be initialized at declaration time.

const maxItems = 30; // Valid constant const name; // syntax error: not initialized const minItems = 5; minItems = 6; // Throw an errorCopy the code

Template string

Template strings are enhanced strings that use backquotes (‘) around regular strings. It can be used as a regular string, it can be used to define multi-line strings, or it can be used to embed variables in strings.

// Let message = 'Hello world! `; console.log(message); // Hello world! // To include backquotes in a string, just use a backslash (\) escape to let message = '\' Hello\ 'world! `; console.log(message); // `Hello` world! // Multiline string (just include a newline in the desired position) let message = 'Multiline string'; console.log(message); // "Multiline // string" console.log(message.length); // 16 // All whitespace inside the backquotes are part of the string, so be careful about indentation. let message = `Multiline string`; console.log(message); // "Multiline // string" console.log(message.length); Var name = "Bob", time = "today"; console.log(`Hello ${name}, how are you ${time}? `) // Hello Bob, how are you today?Copy the code

To replace a

The template string substitution bit is identified by ${}. Inside the braces can be any JavaScript expression, such as variable names, operations, function calls, and references to object properties.

Var name = "Nicholas"; var message = `Hello, ${name}.`; console.log(message); Var x = 1; var x = 1; var y = 2; The console. The log (` ${x} + ${} y = ${x + y} `) / / 1 + 2 = 3 console. The log (` ${x} + ${2} y * = ${x + y * 2} `) / / 1 + 4 = 5 / / function calls function fn() { return "Hello World"; } console.log(' foo ${fn()} bar ') // foo Hello World bar // Object attribute var obj = {x: 1, y: 2}; console.log(`${obj.x + obj.y}`)Copy the code

function

Default values for function arguments

In ES5 or earlier, we might use the following pattern to create functions with parameter defaults:

function add(x, y) { x = x || 20; y = y || 30; return x + y; } console.log(add()); / / 50Copy the code

There is a drawback to this method: if the argument x or y is assigned, but the corresponding Boolean is false, the assignment does not work. A safer alternative in this case is to use typeof to detect the typeof the parameter, as shown in the following example:

function add(x, y) { x = (typeof x ! == "undefined") ? x : 20; y = (typeof y ! == "undefined") ? x : 30; / /... }Copy the code

The default values of the ES6 function arguments are as follows:

function add(x = 20, y = 30) {
    return x + y;
}Copy the code

As you can see, ES6 is much cleaner and more natural than ES5.

Rest parameters and extension operators

You can read about these two parts here

Arrow function

One of the most interesting new parts of ES6 is the Arrow function. Arrow functions are defined using arrows (=>). Let’s look at the differences between arrow functions and traditional functions:

// ES6
var f = () => 5;
// ES5
var f = function () { return 5 };
// ES6
var sum = (num1, num2) => num1 + num2;
// ES5
var sum = function(num1, num2) {
  return num1 + num2;
};Copy the code

If the arrow function has more than one statement in its code block, enclose them in braces and return them with a return statement.

const foo = () => {
   const a = 20;
   const b = 30;
   return a + b;
}Copy the code

One use of the arrow function is to simplify the callback function.

// ES5 [1,2]. Map (function (x) {return x * x; }); // ES6 [1,2,3]. Map (x => x * x);Copy the code

Arrow functions can replace function expressions, but not function declarations

Note the following when using arrow functions:

  • Can’t changethisThe value of: this cannot be modified inside a function; it will be during the life of the function

    Stay the same.
  • No Arguments objects: Since arrow functions have no arguments binding, you must rely on named or residual arguments to access function arguments.
  • Can’t be usednewCall: Arrow functions have no [[Construct]] method and therefore cannot be used as constructors

    The number, the use ofnewCalling the arrow function throws an error.
  • No prototype: since you can’t use it with arrow functionsnew, then it doesn’t need a prototype, i.e., none

    The prototype properties.

Extension of object literal syntax

Short for properties and methods

Function f(x, y) {return {x, y}; Function f(x, y) {return {x: x, y: y}; } f(1, 2) // Object {x: 1, y: 2} var o = {method() {return "Hello! ; }}; Var o = {method: function() {return "Hello! ; }};Copy the code

Attribute names need to be computed

The JavaScript language defines attributes of objects in two ways.

var person = {}, lastName = "last name"; Person ["first name"] = "Nicholas"; Person [lastName] = "Zakas"; console.log(person["first name"]); // "Nicholas" console.log(person[lastName]); // "Zakas"Copy the code

However, if you define objects in a literal fashion (using braces), you can only define properties using method one in ES5.

var person = {
    "first name": "Nicholas"
};
console.log(person["first name"]); // "Nicholas"Copy the code

In ES6, the evaluated attribute name is part of the object literal syntax, which is also expressed in square brackets.

var lastName = "last name"; var person = { "first name": "Nicholas", [lastName]: "Zakas" }; console.log(person["first name"]); // "Nicholas" console.log(person[lastName]); // "Zakas" // Can also be the expression var suffix = "name"; var person = { ["first" + suffix]: "Nicholas", ["last" + suffix]: "Zakas" }; console.log(person["first name"]); // "Nicholas" console.log(person["last name"]); / / / / "Zakas" can also be used to represent the method name var obj = {[' h '+' ello '] () {the console. The log (" hi "); }}; obj.hello() // hiCopy the code

Deconstruction assignment

Deconstructing assignment is also a very common feature in ES6. Extracting values from arrays and objects and assigning values to variables following a pattern is called Destructuring.

Object to deconstruct

Object destruct syntax uses object literals on the left side of assignment statements, for example:

let node = {
    type: "Identifier",
    name: "foo"
};
let { type, name } = node;
console.log(type); // "Identifier"
console.log(name); // "foo"Copy the code

In this code, the value of Node. type is stored in the type local variable, and the value of Node. name is stored in the name variable.

When using a destruct assignment statement, the specified local variable is assigned to undefined if no property of the same name is found in the object. Such as:

let node = {
    type: "Identifier",
    name: "foo"
};
let { type, name, value } = node;
console.log(type); // "Identifier"
console.log(name); // "foo"
console.log(value); // undefinedCopy the code

Optionally, we can define a default value to use if the specified property does not exist. Something like this:

let node = {
    type: "Identifier",
    name: "foo"
};
let { type, name, value = true } = node;
console.log(type); // "Identifier"
console.log(name); // "foo"
console.log(value); // trueCopy the code

The examples above all use property names in the object as local variable names. But ES6 allows us to use a different name when assigning values to local variables. Something like this:

let node = { type: "Identifier", name: "foo" }; let { type: localType, name: localName } = node; console.log(localType); // "Identifier" console.log(localName); // "foo" // We can also add default values to variable aliases let node = {type: "Identifier"}; let { type: localType, name: localName = "bar" } = node; console.log(localType); // "Identifier" console.log(localName); // "bar"Copy the code

Array structure

The syntax for array deconstruction looks very similar to object deconstruction, except that object literals are replaced with array literals. Look directly at examples:

let colors = [ "red", "green", "blue" ]; let [ firstColor, secondColor ] = colors; console.log(firstColor); // "red" console.log(secondColor); Let colors = ["red", "green", "blue"]; let [ , , thirdColor ] = colors; console.log(thirdColor); // "blue" // You can also add the default let colors = ["red"]; let [ firstColor, secondColor = "green" ] = colors; console.log(firstColor); // "red" console.log(secondColor); // "green"Copy the code

String structure

Strings can also be structurally assigned.

const [a, b, c, d, e] = 'hello';
console.log(a) // "h"
console.log(b) // "e"
console.log(c) // "l"
console.log(d) // "l"
console.log(e) // "o"Copy the code

Parameters of the structure

function add([x, y]){ return x + y; } add([1, 2]); Function move({x = 0, y = 0} = {}) {return [x, y]; } move({x: 3, y: 8}); // [3, 8] move({x: 3}); // [3, 0] move({}); // [0, 0] move(); / / [0, 0]Copy the code

The module

The function of the module consists of two commands: export and import. The export command is used to specify the external interface of a module, and the import command is used to input functions provided by other modules.

The export command

Export var color = "red"; export let name = "Nicholas"; export const magicNumber = 7; Export function sum(num1, num2) {return num1 + num1; } Rectangle class Rectangle {constructor(Rectangle, width) {this. Rectangle = Rectangle; this.width = width; Var color = "red"; var color = "red"; export let name = "Nicholas"; export const magicNumber = 7; export {color, name, magicNumber}; Function sum(num1, num2) {return num1 + num1; } export {sum as addCopy the code

The import command

// import a single import {color} from "./example.js"; Import {color, name, sum} from "./example.js"; Import {color as redColor} from "./example.js"; Import * as example from "./example.js";Copy the code

Export default values using the default keyword

Export default function(num1, num2) {return num1 + num2; } function sum(num1, num2) {return num1 + num2; } export default sum; Function sum(num1, num2) {return num1 + num2; } export { sum as default };Copy the code

Importing the default value is also different

import sum from "./example.js"; // There are no curly braces. console.log(sum(1, 2)); / / 3Copy the code

Afterword.

This is just a summary of some common ES6 features, as well as promises, classes, etc., which may be left for another time due to space issues.