In this article we will introduce some of the new features commonly used in ES2015 / ES6

1. Variable definition

Before ES6, variables could only be defined using the var keyword. In ES6, the let and const keywords were added. The differences are as follows:

The keyword scope Whether the variable is promoted Can I repeat the definition
var Function scope is can
let,const Block-level scope no no
function function_scope() {
    console.log(result) // undefined
    var result = 0
    for (var count = 1; count <= 5; count++) { result += count }
    console.log(count) / / 5
    return result
}

function block_scope() {
    // console.log(result) -> ReferenceError: result is not defined
    let result = 0
    for (let count = 1; count <= 5; count++) { result += count }
    // console.log(count) -> ReferenceError: count is not defined
    return result
}
Copy the code

The difference between let and const is as follows:

  • useconstA defined variable must be assigned when declared, andletDon’t have to
  • useconstA defined variable cannot be modified after it is declared, whileletDon’t
// const a -> Uncaught SyntaxError: Missing initializer in const declaration
const a = 0
// a = 1 -> Uncaught TypeError: Assignment to constant variable.
Copy the code

Note that by immutable, we do not mean that the value of a variable cannot be modified, but that its identifier cannot be reassigned

To be precise, const declares a variable as a read-only reference to a value, which means that the address in stack space is immutable, not the value in heap space

Therefore, we can still modify the value of a reference type

const a = [1.3.5]
a[0] = 2
console.log(a) // (3) [2, 3, 5]
Copy the code

2. Array iteration

Prior to ES6, there were two ways to use a for loop to iterate over an array: traditional for loops and for… In circulation

let array = ['a'.'b'.'c']
// The traditional for loop
for (let index = 0; index < array.length; index++) {
    console.log(index + ':' + array[index])
}
// for... In circulation
for (let index in array) {
    console.log(index + ':' + array[index])
}

/* * Result: * 0: a * 1: b * 2: c **/
Copy the code

In ES6, for… The of loop allows you to iterate over a list of elements rather than an array index

let array = ['a'.'b'.'c']
// for... Of circulation
for (let item of array) {
    console.log(item)
}

/* * Result: * a * b * c **/
Copy the code

In the for… Continue and break statements can also be used in the OF loop

let array = [1.2.3.4.5.6.7.8]
let sum = 0
for (let item of array) {
    if (item % 2= = =0) continue
    sum += item
}
console.log(sum) / / 16
Copy the code

3. Template string

Template strings are handy in scenarios such as multi-line strings and string concatenation

  • Before the ES6
// Multi-line string
let html = '<ul>' + 
    '<li>Apple</li>' +
    '<li>Banana</li>' +
    '<li>Cherry</li>' +
    '</ul>'
console.log(html)
// String concatenation
let protocol = 'https'
let host = '127.0.0.1'
let port = '80'
let path = 'index.html'
let url = protocol + ': / /' + host + ':' + port + '/' + path
console.log(url) / * * / http://127.0.0.1:80/index.html
Copy the code
  • After the ES6
// A multi-line string, retain the original format
let html = ` 
      
  • Apple
  • Banana
  • Cherry
`
console.log(html) // String concatenation, you can use variables let protocol = 'https' let host = '127.0.0.1' let port = '80' let path = 'index.html' let url = `${protocol}: / /${host}:${port}/${path}` console.log(url) / * * / http://127.0.0.1:80/index.html Copy the code

4. Deconstruct grammar

Destruct syntax extracts values from arrays and objects and assigns them to new variables

  • Before the ES6
// Array destruct
let array = ['a'.'b'.'c']
let x = array[0]
let y = array[1]
let z = array[2]
console.log(x, y ,z) // a b c
// Object destruct
let object = { name: 'Steve'.age: 18 }
let name = object.name
let age = object.age
console.log(name, age) // Steve 18
Copy the code
  • After the ES6
// Array destruct
let array = ['a'.'b'.'c']
let [x, y, z] = array
console.log(x, y, z) // a b c
// Destruct the object with the same variable name as the property name
let object = { name: 'Steve'.age: 18 }
let { name, age } = object
console.log(name, age) // Steve 18
Copy the code

Destruct syntax can also set default values and rename variables

// Set the default value
let array = ['a'.'b']
let [x = 'x', y = 'y', z = 'z'] = array
console.log(x, y, z) // a b z
// Rename variables
let object = { name: 'Steve'.age: 18 }
let { name: nickName, age: nominalAge } = object
console.log(nickName, nominalAge) // Steve 18
Copy the code

5. Extend operators

  • Before the ES6
// Array copy
let array = ['a'.'b'.'c']
let array_copy = array.concat()
console.log(array_copy) // (3) ["a", "b", "c"]
// Array merge
let array_one = ['a'.'b'.'c']
let array_two = ['d'.'e'.'f']
let array_merge = array_one.concat(array_two)
console.log(array_merge) // (6) ["a", "b", "c", "d", "e", "f"]
// Receives function arguments. All arguments passed in are stored in arguments
function add() {
    let result = 0
    Array.prototype.forEach.call(arguments.function(item) { result += item })
    return result
}
let result = add(1.2.3)
console.log(result) / / 6
Copy the code
  • After the ES6
// Array copy
let array = ['a'.'b'.'c']
let array_copy = [...array]
console.log(array_copy) // (3) ["a", "b", "c"]
// Merge arrays
let array_one = ['a'.'b'.'c']
let array_two = ['d'.'e'.'f']
let array_merge = [...array_one, ...array_two]
console.log(array_merge) // (6) ["a", "b", "c", "d", "e", "f"]
// The remaining parameters are taken as the last parameter of the function and stored as an array
function add(. array) {
    let result = 0
    array.forEach(function(item) { result += item })
    return result
}
let result = add(1.2.3)
console.log(result) / / 6
Copy the code

6. Default parameters

When defining a function, you can set default values for function parameters directly

  • Before the ES6
function greet(somebody) {
    var somebody = somebody || 'stranger'
    console.log('Hello, ' + somebody)
}
greet('Amy') // Hello, Amy
greet() // Hello, stranger
Copy the code
  • After the ES6
function greet(somebody = 'stranger') {
    console.log('Hello, ' + somebody)
}
greet('Amy') // Hello, Amy
greet() // Hello, stranger
Copy the code

Arrow function

Using the arrow function not only makes it easier to define functions, but the value of this inherits the value of the parent execution context this

  • Before the ES6
// Filter odd numbers, element summation
let sum = 0
let arr = [1.2.3.4.5]
let even = arr.filter(function(item) { return item % 2= = =0 })
even.forEach(function(item) { sum = sum + item })
console.log(sum) / / 6
/ / this value
let object = {
    value: 'hello'.print: function() {
        // Use the bind function to bind this
        setTimeout(function() { console.log(this.value) }.bind(this), 1000)
    }
}
object.print() // hello
Copy the code
  • After the ES6
// Filter odd numbers, element summation
let sum = 0
let arr = [1.2.3.4.5]
let even = arr.filter((item) = > (item % 2= = =0))
even.forEach((item) = > { sum = sum + item })
console.log(sum) / / 6
/ / this value
let object = {
    value: 'hello'.print: function() {
        // Using the arrow function, the value of this inherits the value of this from the parent execution context (in this case, the print function)
        setTimeout(() = > { console.log(this.value) }, 1000)
    }
}
object.print() // hello
Copy the code