javascript learning notes (ES6's most commonly used syntax)

Keywords: REST Javascript

Common features of ES6

let,const

ES5 has only global scope and function scope, but no block level scope. Let adds a block level scope to JavaScript. The variables it declares are only valid in the code block where the let command is located.

{
    {
        let a = 1;
        let b = 1;
        console.log(a);// 1
        console.log(b);// 1
    }
    console.log(a);// a is not defined
    console.log(b);// 1
    for (let i = 0; i < 10; i++) {
        //...
    }
    console.log(i); // i is not defined
    for (var j = 0; j < 10; j++) {
        //...
    }
    console.log(j);//10
}

const is also used to declare constants. Once declared, the value of a constant cannot be changed.

const PI = 3.1415926
PI = 3.14;// Assignment to constant variable

Default parameters

ES6 handles the default parameters, basically using the following methods

function toDecimal(number, precision) {
    var precision = precision||2;
    var temp = 1;
    for (let i = 0; i < precision; i++) {
        temp = temp * 10;
    }
    return Math.round(number * temp)/temp;
}

ES6 can be written as follows

function toDecimal(number, precision = 2) {
    var temp = 1;
    for (let i = 0; i < precision; i++) {
        temp = temp * 10;
    }
    return Math.round(number * temp)/temp;
}

Template object

Before ES6, string objects are spliced in the following way

var firstName = 'Fei';
var lastName = 'Zhang';
console.log('your name is ' + firstName + ' ' + lastName + '.');

You can use ${} in ES6

var firstName = 'Fei';
var lastName = 'Zhang';
console.log('your name is ${firstName} %{lastName}.');

Multiline string

String wrapping before ES6, generally using \ n

var strTemp = 'abcdefg\n'+
    'hijklmn\n';
console.log(strTemp);

ES6 just need the back quote

var strTemp = ·abcdefg
    hijklmn·;
console.log(strTemp);

Arrow function = >

=>function can be written in a simple and clear way

function(i){ return i + 1; } // ES5
(i) => i + 1; // ES6

function(x, y) {
    x++;
    y--;
    return x + y;
}
(x, y) => {x++; y--; return x+y}

When using anonymous functions, you do not need to define additional variables to point to this

// ES5
var obj = this;
foo(function(){
    obj.foo1();
});
// ES6
foo(()=>{this.foo1();});

Deconstructing

ES6 allows you to extract values from arrays and objects and assign values to variables according to certain patterns.

let cat = 'cat'
let dog = 'dot'
let zoo = {cat: cat, dog: dog} // es5
let zoo1 = {cat, dog} // es6
// It can also be written in reverse
let {cat1, dog1} = zoo;

rest parameter ( Variable name)

The variable with rest parameter is an array, which can use all operations of the array

function sum(...values){
    let temp = 0;
    for (var value of values){
        temp = temp+ value;
    }
    return temp;
}

Posted by Skunkmaster on Sun, 03 May 2020 06:34:42 -0700