Learn ES6 grammar quickly and get started at the fastest speed

Posted by 5kyy8lu3 on Wed, 02 Mar 2022 08:39:58 +0100

(1) let command

ES6 adds the let command to declare variables. Its usage is similar to var, but the declared variables are only valid in the code block where the let command is located

{
  let a = 10;
  var b = 1;
}

a // ReferenceError: a is not defined.
b // 1

What is a code block? In short, it is something in {}. Previously, JS did not have a block level scope. We will use self executing anonymous functions to simulate the block level scope

function outputNumbers(count){
    (function () {
        for (var i=0; i < count; i++){
            alert(i);
        }
    })();
    alert(i); //Cause an error!
}

In ES6, we have let. The variables defined by let cannot be accessed in the external environment. The most suitable place to use let is the for loop

for (let i = 0; i < 10; i++) {
    console.log(i)
}
console.log(i) //report errors

This avoids the embarrassing situation of using var to define i variables after i execution When using let, we should pay attention to the difference between let and var is that there is no variable promotion

// var situation
console.log(foo); // Output undefined
var foo = 2;

// let the situation
console.log(bar); // Error ReferenceError
let bar = 2;

Calling the variable before the let life variable will make a mistake, and the way var handles is to declare the declaration ahead of time and the assignment operation is kept in place. We all know that VaR only returns the unfdinded if it is declared unassigned. We call the area before let declares the variable "temporary dead zone" (TDZ) of the variable. In addition, let is not allowed to declare repeatedly

function () {
  let a = 10;
  var a = 1;
}

// report errors
function () {
  let a = 10;
  let a = 1;
}

(2) const command

const declares a read-only constant. Once declared, the value of the constant cannot be changed.

const PI = 3.1415;
PI // 3.1415

PI = 3;
// TypeError: Assignment to constant variable.

The above code indicates that changing the value of the constant will report an error. The variable declared by const must not change its value, which means that once const declares the variable, it must be initialized immediately and cannot be left for later assignment.

const foo;
// SyntaxError: Missing initializer in const declaration

The above code indicates that for const, if it only declares that it does not assign a value, an error will be reported.

const has the same scope as the let command: it is valid only within the block level scope where the declaration is located.

if (true) {
  const MAX = 5;
}
MAX // Uncaught ReferenceError: MAX is not defined

The constant declared by const command is not promoted, and there is also a temporary dead zone, which can only be used after the declared position.

if (true) {
  console.log(MAX); // ReferenceError
  const MAX = 5;
}

The above code is called before the constant MAX declaration, and the result is an error.

const is a constant declared. Like let, it cannot be declared repeatedly.

var message = "Hello!";
let age = 25;

// The following two lines will report errors
const message = "Goodbye!";
const age = 30;

const command is more suitable for defining variables that do not need to be changed once defined, such as url address.

About top-level objects

As we all know, the variables and functions defined by global var in ES5 are actually the attributes of the global object window (global), while in ES6, in order to maintain compatibility, the global variables declared by var command and function command are still the attributes of the top-level object; On the other hand, it is stipulated that the global variables declared by let command, const command and class command do not belong to the properties of the top-level object. In other words, starting from ES6, global variables will be gradually decoupled from the properties of the top-level object.

var a = 1;
// In the REPL environment of the Node, it can be written as global a
// Or use the general method to write this a
window.a // 1

let b = 1;
window.b // undefined

In the above code, the global variable a is declared by the var command, so it is an attribute of the top-level object; The global variable b is declared by the let command, so it is not a property of the top-level object and returns undefined.

(3) Deconstruction and assignment of variables

This part is some new assignment methods added in ES6. I will give an example for each part, as long as others can understand the code when using it.

1. Array deconstruction and assignment

Previously, when assigning values to variables, you could only specify values directly.

let a = 1;
let b = 2;
let c = 3;

ES6 allows you to write as follows.

let [a, b, c] = [1, 2, 3];
2. Deconstruction and assignment of objects

Deconstruction can be used not only for arrays, but also for objects.

let { foo, bar } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"
3. Deconstruction and assignment of string

Strings can also be deconstructed and assigned. This is because at this point, the string is converted into an array like object.

const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"

Objects like arrays have a length attribute, so this attribute can also be deconstructed and assigned.

let {length : len} = 'hello';
len // 5
4. Deconstruction and assignment of numeric and Boolean values

When deconstructing assignment, if there are numeric and Boolean values to the right of the equal sign, it will be turned into an object first.

let {toString: s} = 123;
s === Number.prototype.toString // true

let {toString: s} = true;
s === Boolean.prototype.toString // true

In the above code, both numeric and Boolean wrapper objects have toString attribute, so the variable s can get the value. The rule of deconstruction assignment is to convert the value to the right of the equal sign into an object as long as it is not an object or array. Since undefined and null cannot be converted into objects, an error will be reported when they are deconstructed and assigned.

let { prop: x } = undefined; // TypeError
let { prop: y } = null; // TypeError
5. Deconstruction and assignment of function parameters

Arguments to functions can also be assigned using deconstruction.

function add([x, y]){
  return x + y;
}

add([1, 2]); // 3

In the above code, the parameter of the function add is an array on the surface, but at the moment of passing in the parameter, the array parameter is solved to form the variables X and y. For the code inside the function, the parameters they can feel are x and y.

6. Default value

Deconstruction assignment allows default values to be specified.

let [foo = true] = [];
foo // true

let [x, y = 'b'] = ['a']; // x='a', y='b'
let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'

javascript Note that ES6 uses the strict equality operator (= = =) internally to judge whether a position has a value. Therefore, if an array member is not strictly equal to undefined, the default value will not take effect.

let [x = 1] = [undefined];
x // 1

let [x = 1] = [null];
x // null

In the above code, if an array member is null, the default value will not take effect, because null is not strictly equal to undefined.