ES6 basic introduction

1, First acquaintance with ES6

es6 compatibility view

1. let and const

  • let, like var, is used to declare variables whose values can be changed
  • const is used to declare constants. Once a constant is initialized, it cannot be re assigned
  • const must be initialized when declared
let name = 'toot toot'
    let age = 18
    const sex = 'female'
  • const is required when you want to prevent re assignment after initialization
  • const is a constant declared, which can be modified without re assignment (reference type)
const person = {
    person.age = 20
    console.log(person.age) // 20
  • When you are uncertain about the type to be declared, you can first declare it as const, and then change it to let if you need to change it later

2. Differences among let, const and var

2.1 repeated declaration

  • Repeated declaration: the existing variable or constant is declared again
  • var allows duplicate declarations
  • let and const cannot be declared repeatedly
function fun(name) {
      let name = 'dudu'
    fun('toot toot')

2.2 variable lifting

  • var will promote the declaration of variables to the top of the current scope, that is, "can be used before declaration"
    var name = 'dudu'
  • let and const do not have variable promotion, that is, they must be "declared before use"

2.3 temporary dead zone

  • Temporary deadband: as long as there are let and const in the scope, the constants or variables declared by them will be automatically "bound" to this area and will no longer be affected by the external scope
let name = 'dudu'
    function fun() {
      // If there is a let in the scope, the internal scope will be bound,
      // When using the console, you can only find the corresponding name internally, not externally,
      // So it will report an error
      let name = 'toot toot'

  • var has no temporary dead zone

2.4 properties and methods of window objects

  • In the global scope, the variable declared by var or the function declared by function will automatically become the attribute or method of window object (which can be used through
var name = 'dudu'
    function fun() { }
    console.log( // 'dudu'
    console.log( === fun) // true

2.5 block level scope

  • Block level scope: function() {}, for() {}, while() {}, do{}while(), if() {}, switch, etc
  • Object has curly braces but no scope
  • var has no block level scope
  • let and const have block level scope

Two. Template string '.

  • The template string is the back quote ` ` (the key below the esc key in the upper left corner of the keyboard can only be pressed in English)
  • Template string splicing variable is through ${variable}
 let name = 'toot toot'
    const info = `hello,I am ${name}`
  • In the template string, all spaces, line breaks and indents will be reserved for output (output as you write)
  • If you want to output ` or \, the template string needs to pass the escape character\
console.log(`Output a backquote \``)
    console.log(`Output backslash \\ `)
  • For the injection of ${} into the template string, constants, variables, object attributes, calling functions, JS expressions, etc. can be placed inside the brackets, and finally a value can be obtained

3, Arrow function

  • Writing method of arrow function: () = > {}
  • The arrow function is an anonymous function. If it needs to be called elsewhere, it can be assigned to a constant or variable
onst add = (x,y) => {
      return x + y

3.1 simplification of arrow function

3.1.1 single parameter

  • The arrow function of a single parameter can not write the parentheses of the parameter, that is: parameter = > {}
const add = x => {
      return x + 5
  • If there are multiple parameters or no parameters, parentheses cannot be omitted

3.1.2 single line function body

  • For single line function body, you can omit curly braces {} and return keyword at the same time, that is: () = > single line function body
const add = (x,y) => x + y

3.1.3 single line object

  • For single line objects, you can omit the curly bracket and return keyword of the function body, and then add a parenthesis () outside the curly bracket {} of the object
// Before simplification
const add = (x,y) => {
      return {
        value: x + y
// After simplification
const add = (x,y) => ({
        value: x + y

3.2 this pointing

3.2.1 this direction in ordinary functions

  1. this points to the window object in the global scope
  2. Ordinary functions can only determine the point of this when calling the function, which is only related to who calls it and has nothing to do with where to call it

Reference articles

  • Rule 1: when an object calls a function, this points to the object to be dotted

Object Method ()

var obj1 = {
       fn() {
   var obj2 = {
   obj2.fn() // Obj2 calls, so this is obj2. Then, the function is also a reference type. When assigning values, it will point to the same heap, so 7 will be printed
function outer() {
       var a = 20
       var b = 12
       return {
           fn() {
   outer().fn() // outer() returns an object, so it finally forms an object Method, this will point to the returned object, so 77 will be printed
  • Rule 2: if the parentheses call the function directly, this points to the window object

Function ()

var obj1 = {
       fn() {
   var a = 3
   var b = 4
   var fn = obj1.fn
   fn() //Call the function directly, and this points to the window object, and the result will return 7
function fn() {
       return this.a + this.b
   var a = 1
   var b =2
   var obj = {
   var result = obj.fn() //By calling in the form of object, this points to obj object, a=3,b:fn() is equivalent to calling FN method globally, and this in b points to window, so b=3
   console.log(result) // 6
  • Rule 3: array (class array object) count out the function to call, and this points to this array (class array object)
    • Class array objects: all objects whose key names are natural number sequences (starting from 0) and have length attribute
    • The arguments object is the most common class array object, which is a list of arguments to a function

Array [subscript] ()

function fun() {
    fun('A','B','C',function() {
        console.log(this[1]) // this points to the arguments class array object 'A','B','C',function(), and the result output is B
  • Rule 4: the function in IIFE, this points to the window object

(function() {

var a = 1
    var obj = {
            var a = this.a; //this in IIFE points to window, then a=1
            return function() {
                // A is inside the function body, then a=1
                // return returns a function
                console.log(a + this.a) // 3
    } //If the function is called in the way of point, then this points to the obj object, then this a=2
  • Rule 5: the timer and delayer call the function, and this points to the window object

Setinterval (function, time)
SetTimeout (function, time)

var obj = {
        fun() {
            console.log(this.a + this.b) 
    var a = 3
    var b = 4
    setTimeout(, 2000); //This points to window, then this a=3,this. b=4
    setTimeout(() => { //If the function is called in the form of object point method, this points to obj object, this a=1,this.b=2
    }, 2000);
  • Rule 6: the context of the event handler is the DOM element that binds the event
DOM element.onclick = function() {
//When there are other functions inside the function, such as timer, the direction of this should be considered
// If necessary, you need to back up this, that is, var_ This = this, which can be used in the internal function_ This points to the DOM you want
  • Rule 7: this of the constructor points to the object generated after the constructor is instantiated

3.2.2 this direction in arrow function

  • The arrow function does not have its own this. It will capture the this value of the context in which it is located (i.e. the defined location) as its own this value, that is, it will inherit the parent's this

3.3 scenario not applicable to arrow function

  1. As a constructor, it is not suitable to use arrow function
  2. When this is required to point to the calling object, such as binding events to DOM
  3. When you need to use arguments, it is not suitable to use the arrow function, because the arrow function does not have arguments

4, Deconstruction assignment

4.1 deconstruction and assignment of array

4.1.1 principle of deconstruction assignment

  • Pattern (structure) matching: if the right side is an array, the left side is also an array []
[] = [1,2,3]
  • The assignment is completed if the index value is the same
[a,b,c] = [1,2,3]  // a=1,b=2,c=3
  • Negligible: if assignment is not required, comma can be used to skip
// Get 1,4,6
    const [a,[,,b],c] = [1,[2,3,4,5],6]
    console.log(`${a}   ${b}   ${c}`) // 1   4   6

4.1.2 default value of array deconstruction assignment

  • When the data cannot be matched or the matched data is undefined (only undefined, null is not allowed), the default value will be used
  • The default value is set on the left
const [a=1,b=2] = []
  • The default expression is evaluated only if it is lazy

4.1.3 deconstruction and assignment of common class arrays

  1. arguments
    It is used to get the parameters passed. It is a class array object
 function fun() {
      console.log(arguments) // Arguments(3) [2, 3, 4, callee: ƒ, Symbol(Symbol.iterator): ƒ]
  • The deconstruction assignment of arguments is the same as that of an array
  1. NodeList
    A class array object
<p>I'm 1</p>
<p>I'm 2</p>
<p>I'm 3</p>
  const [p1,p2,p3] = document.querySelectorAll('p')
  console.log(p1)  //<p>I'm 1</p>
  console.log(p3) // <p>I'm 3</p>

4.1.4 deconstruction and assignment of function parameters

const array = [6,21]
  const add = ([x,y]) => x+y
  console.log(add(array)) //27

4.1.5 exchange variables

 let x = 92;
  let y = 23;
  [x,y] = [y,x]
  console.log(x,y) // 23 92

Deconstruction of assignment object 2.4

4.2.1 principle of object deconstruction assignment

  • Pattern (structure) matching: curly bracket {} on the left
  • The assignment is completed if the property name is the same
  const {name,age} = {
  • The attribute name and attribute value are the same and can be abbreviated
  • During deconstruction assignment, if you need to change the attribute name, you can modify the original attribute name on the left: the modified attribute name
	name:name ===> Abbreviated as name that will do
	name:nickname // Changed to nickname

4.2.2 precautions for object deconstruction and assignment

  1. Default value
  • When the attribute value of the object is strictly equal to (= =) undefined, the corresponding default value will take effect
  • The default value is set by the equal sign =
const {name='toot toot',age} = {
  console.log(name) // toot toot
  console.log(age) // 23
  • The default expression is evaluated only if it is lazy
  1. Use a declared variable for deconstruction assignment
  • At this time, you need to wrap the contents of the deconstruction assignment with parentheses
let name = 'toot toot';
  ({name}= {name:'dudu'})
  console.log(name) // dudu
  1. The deconstruction assignment of the object can obtain the inherited properties
  2. For deconstruction assignment when the function parameter is used as an object, the parentheses of the parameter cannot be omitted
const info = ({name,age}) => console.log(`I am ${name},this year ${age}year~~`)
  let person = {
    name:'toot toot',
  • If there are unnecessary attributes in the structure assignment of the object, you can write them directly without using commas
const PLAYER = {
            nickname:"A greedy snake",
            master:'Dragon King of the East China Sea',
                skillName:'Long Yin',
                skillName:'Tornado rain blow',
                skillName:'Long Teng',
        const { master } = PLAYER //When taking the second element, you don't need to use commas to ignore the first one, you can take it directly
        console.log(master) //'dragon king of the East China Sea '
        const {skill:[skill1,{skillName},{skillName:skillName3}]} = PLAYER
       console.log(skillName) //Tornado rain blow
       console.log(skillName3) // Long Teng

4.3 other types of deconstruction assignment

4.3.1 deconstruction and assignment of string

  1. Array form
    Match by order (space delimited)
let  str = 'hello'
  const [a,b,,,c] = str
  console.log(a+'  '+b+'   '+c) // h  e   o
  1. Object form
 let  str = 'hello'
  const {0:a,1:b,4:c} = str
  console.log(a+'  '+b+'   '+c) // h  e   o 

4.3.2 deconstruction and assignment of numeric and Boolean values

  • The value to the right of the equal sign will be converted into an object, and then the object will be deconstructed and assigned

4.3.3 deconstruction assignment of undefined and null

  • Because undefined and null cannot be converted into objects, using their deconstruction assignment will report an error

5, Enhancement of object literals

5.1 concise representation of attributes and methods

  • Attribute: when the key name is consistent with the variable name or constant name, it can be abbreviated to one
  • Method: colon and function keyword can be omitted
let name = 'dudu'
  const person = {
    name, // Equivalent to: name:name
    sayhello() {} // sayhello:function() {}

5.2 square bracket syntax

  • Square bracket syntax before ES6: Reference article Explanation of access properties
  • The square bracket syntax of ES6 can be written in the object literal
const prop = 'name'
  const person = {
    [prop]:'toot toot'
  console.log(person) // {name: 'beep'}
  • Values can be placed in square brackets or values (expressions) that can be obtained by calculation

6, Default values for function parameters

  • When a function is called, the parameters passed are used; If no parameters are passed, the default value is used
  • The default value can be assigned directly with the equal sign
  • Do not pass the parameter or explicitly pass undefined as the parameter. The default value will take effect only in these two cases
  • The default value of an expression is evaluated lazily
  • The default value of function parameters should be set from the right side of the parameter list. If you start from the left, you need to set the value of the corresponding parameter to undefined when calling the function to use the default value
 const multiply = (x=2,y) => x*y

Keywords: Javascript Front-end ECMAScript

Added by toledojimenez on Wed, 09 Mar 2022 10:00:51 +0200