Ruan Yifeng great God ECMAScript 6 Introduction notes sorting

Ruan Yifeng great God ECMAScript 6 beginner level:

If you don't like the typesetting here, you can go to my YuQue to have a look. YuQue is really unique

let and const commands

  • The variable declared by let is only valid in the code block in which it is located.


  • The variable i is declared by the var command and is valid in the global scope, so there is only one variable i in the global scope.
  • The variable i is declared by let. The current i is only valid in this cycle, so the i of each cycle is actually a new variable


  • In addition, a special feature of the for loop is that the part where the loop variable is set is a parent scope, while the interior of the loop body is a separate child scope.
for (let i = 0; i < 3; i++) {
  let i = 'abc';
// abc
// abc
// abc


  • ES6 clearly stipulates that if there are let and const commands in the block, the variables declared by the block for these commands form a closed scope from the beginning. If these variables are used before declaration, an error will be reported. That is, there is no variable promotion.


  • The essence of temporary deadband is that as soon as you enter the current scope, the variable to be used already exists, but it cannot be obtained. You can obtain and use the variable only when the line of code declaring the variable appears.


  • let is not allowed to declare the same variable repeatedly within the same scope.
function func(arg) {
  let arg;        //Parameters cannot be redeclared inside a function.
func() // report errors

function func(arg) {
    let arg;
func() // No error reporting


  • Allows functions to be declared within a block level scope.
  • Function declarations are similar to var, that is, they are promoted to the head of the global scope or function scope.
  • At the same time, the function declaration is also promoted to the head of the block level scope.
//The function declaration statement inside the block level scope is not recommended
  let a = 'secret';
  function f() {
    return a;
//Within a block level scope, function expressions are preferred
  let a = 'secret';
  let f = function () {
    return a;


  • Once const declares a variable, it must be initialized immediately and cannot be assigned later.


  • const actually guarantees that the value of the variable cannot be changed, but the data stored at the memory address pointed to by the variable cannot be changed.


  • ES6 has six methods to declare variables.

var command and function command. let and const commands, import commands and class commands.


  • On the one hand, ES6 stipulates that 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.


  • In the global environment, this returns the top-level object. However, in Node module and ES6 module, this returns the current module.
  • This in the function, if the function is not run as a method of the object, but simply as a function, this will point to the top-level object. However, in strict mode, this will return undefined.


Deconstruction and assignment of variables

  • ES6 allows you to extract values from arrays and objects and assign values to variables according to a certain pattern, which is called deconstruction.
  • If the deconstruction fails, the value of the variable is equal to undefined.


  • The elements of the array are arranged in order, and the value of the variable is determined by its position;
  • The attributes of the object have no order, and the variable must have the same name as the attribute in order to get the correct value.


let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"
let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa"
foo // error: foo is not defined
//In the code above, foo Is a matching pattern, baz Is the variable. What is really assigned is the variable baz,Not a pattern foo. 
const node = {
  loc: {
    start: {
      line: 1,
      column: 5

let { loc, loc: { start }, loc: { start: { line }} } = node;
line // 1
loc  // Object {start: Object}
start // Object {line: 1, column: 5}
// report errors
let {foo: {bar}} = {baz: 'baz'};


  • Object deconstruction can also specify default values.
var {x = 3} = {};
x // 3

var {x, y = 5} = {x: 1};
x // 1
y // 5

var {x: y = 3} = {};
y // 3

var {x: y = 3} = {x: 5};
y // 5

var { message: msg = 'Something went wrong' } = {};
msg // "Something went wrong"
// Wrong writing
let x;
{x} = {x: 1};
// SyntaxError: syntax error

// Correct writing
let x;
({x} = {x: 1});
//Only do not write braces at the beginning of the line to avoid JavaScript This problem can only be solved by interpreting it as a code block.


  • Strings can also be deconstructed and assigned.
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"


  • As long as the value of the object is assigned to the equal sign or the right sign of the array, it will be converted to the value of the object first. Since undefined and null cannot be converted into objects, an error will be reported when they are deconstructed and assigned.


  • Functions can also deconstruct assignment.
[[1, 2], [3, 4]].map(([a, b]) => a + b);
// [ 3, 7 ]


  • Do not use parentheses
    • Variable declaration statement
    • Function parameters
    • Mode of assignment statement
//The following three modes all report errors
let [(a)] = [1];
let {x: (c)} = {};

function f([(z)]) { return z; }

({ p: a }) = { p: 42 };
([a]) = [5];


  • Only the non modal part of the assignment statement can use parentheses.
[(b)] = [3]; // correct
({ p: (d) } = {}); // correct
[(parseInt.prop)] = [3]; // correct



  • Deconstruction and assignment purpose of variable
    • Exchange values of variables
    • Returns multiple values from a function
      • If a function wants to return multiple values, it can only return them in an array or object.
    • Definition of function parameters
      • It is convenient to map a set of parameters to variable names.
    • Extract JSON data
    • The default value of the function parameter is {review
    • Traverse Map structure
      • Any object that deploys the Iterator interface can use for Of loop traversal.
      • The Map structure supports the Iterator interface natively. It is very convenient to obtain the key name and value in conjunction with the deconstruction and assignment of variables.
    • Specify method of input module review
//Exchange variable
let x = 1;
let y = 2;
[x, y] = [y, x];

// Returns an object
function example() {
  return {
    foo: 1,
    bar: 2
let { foo, bar } = example();

//extract JSON Data in object
let jsonData = {
  id: 42,
  status: "OK",
  data: [867, 5309]
let { id, status, data: number } = jsonData;

//ergodic Map structure
const map = new Map();
map.set('first', 'hello');
map.set('second', 'world');
for (let [key, value] of map) {
  console.log(key + " is " + value);
// first is hello
// second is world

// Get key name
for (let [key] of map) {
  // ...

// Get key value
for (let [,value] of map) {
  // ...


Extension of string

Template string

  • It is identified by reverse quotation marks (`). It can be used as an ordinary string, can also be used to define a multi line string, or embed variables in the string.
  • If you need to use back quotation marks in the template string, you should escape it with a back slash.
  • Spaces and newlines of all template strings are reserved and can be eliminated by using the trim method.
  • Variables are embedded in the template string, and the variable name needs to be written in ${}.
  • Functions can also be called in the template string.
  • If the variable in the template string is not declared, an error will be reported.
  There are <b>${basket.count}</b> items
   in your basket, <em>${basket.onSale}</em>
  are on sale!

let greeting = `\`Yo\` World!`;


function fn() {
  return "Hello World";

`foo ${fn()} bar`
// foo Hello World bar


Example: can't understand template compilation

Label template} can't understand


New method of string


  • This method returns a string whose slashes have been escaped (that is, a slash is added before the slash)
  • If the slash of the original string has been escaped, then string Raw() will escape again.
// Actual return "Hi\\n5!",The result after escape is displayed "Hi\n5!"

//why why why?
// `foo${1 + 2}bar`
// Equivalent to
String.raw({ raw: ['foo', 'bar'] }, 1 + 2) // "foo3bar"


Determines whether one string is contained in another

  • includes(): returns a Boolean value indicating whether a parameter string has been found.
  • startsWith(): returns a Boolean value indicating whether the parameter string is at the head of the original string.
  • endsWith(): returns a Boolean value indicating whether the parameter string is at the end of the original string.



Returns a new string, indicating that the original string is repeated n times

If the parameter is decimal, it will be rounded.

If the parameter is negative or Infinity, an error will be reported.

If the parameter is a decimal between 0 and - 1, it is equivalent to 0 because rounding operation will be performed first.
Parameter NaN is equal to 0.

If the parameter is a string, it will be converted to a number first.

'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
'na'.repeat(2.9) // "nana"
'na'.repeat(-0.9) // ""
'na'.repeat(NaN) // ""

//why why why?
'na'.repeat('na') // ""
'na'.repeat('3') // "nanana"




  • If a string is not long enough, it will be completed at the head or tail. padStart() is used for head completion and padEnd() is used for tail completion.
  • If the length of the original string is equal to or greater than the maximum length, the string completion will not take effect and the original string will be returned.
  • If the second parameter is omitted, the default is to use spaces to complete the length.
'x'.padStart(4, 'ab') // 'abax'
'x'.padEnd(5, 'ab') // 'xabab'

'xxx'.padStart(2, 'ab') // 'xxx'

'x'.padStart(4) // '   x'
'x'.padEnd(4) // 'x   '




  • trimStart() eliminates spaces at the beginning of the string and trimEnd() eliminates spaces at the end.
  • They return a new string and do not modify the original string.
const s = '  abc  ';

s.trim() // "abc"
s.trimStart() // "abc  "
s.trimEnd() // "  abc"




  • Returns all matches of a regular expression in the current string

Tags: Javascript

Posted by RedMaster on Wed, 25 May 2022 06:43:55 +0300