Advanced JavaScript - ES6

Posted by phpizza on Mon, 17 Jan 2022 06:58:21 +0100

1, New syntax for ES6

Let: the variables declared by let are valid only at the block level
Variables declared with the let keyword have block level scope.
Variables declared with var do not have block level scope.

<script>
    if (true) {
        let b = 20;
        console.log(b); // 20
    }
    console.log(b);  // b is not defined
</script>

Variable promotion does not exist for variables declared with the let keyword

<script>
    console.log(b);  // Cannot access 'b' before initialization
    let b = 10;
</script>

A variable declared with the let keyword has a temporary deadband
Under the block level scope, variables declared with the let keyword will be bound to the block level scope as a whole and will not be affected by external code.

<script>
    var tmp = 123;
    if (true) {
        tmp = 'abc';  // Cannot access 'tmp' before initialization
        let tmp;
    }
</script>

Exercises

<script>
    var arr = [];
    for (var i = 0; i < 2; i++) {
        arr[i] = function () {
            console.log(i);
        }
    }
    arr[0]();  // 2
    arr[1]();  // 2
</script>
<script>
    var arr = [];
    for (let i = 0; i < 2; i++) {
        arr[i] = function () {
            console.log(i);
        }
    }
    arr[0]();  // 0
    arr[1]();  // 1
</script>

2, const

Declare a constant. A constant is an amount whose value cannot change

Constants declared with const have block level scope

<script>
    if (true) {
        const a = 10;
        console.log(a);  // 10
    }
    console.log(a);  // a is not defined
</script>

A value must be assigned when declaring a constant

<script>
    const a;  // Missing initializer in const declaration
    const b = 10;
</script>

After constant assignment, the value cannot be modified

<script>
    const a = 10;
    const a = 20;  //  Identifier 'a' has already been declared
</script>
<script>
    const ary = [100, 200];
    // The address of the ary constant in memory is not changed.
    ary[0] = 101;
    console.log(ary);  // [101, 200]
    ary = ['a', 'b']  // Assignment to constant variable.
</script>

3, Deconstruction assignment

ES6 allows you to extract values from an array, assign values to variables according to their corresponding positions, and deconstruct objects

Array deconstruction

<script>
    let [a, b, c] = [1, 2, 3]
    console.log(a);  // 1
    console.log(b);  // 2
    console.log(c);  // 3
</script>

let [a, b, c] = [1, 2, 3], let [a, b, c] in [1, 2, 3] represents deconstruction, and what is written in brackets is actually the name of the variable.
The variables in brackets correspond to the values in the right array one by one.

Object deconstruction

According to a certain pattern, extract the value from the array or object, and assign the extracted value to another variable.

<script>
    let person = { name: 'zhangsan', age: 20 };
    let { name, age } = person;
    console.log(name);  // zhangsan
    console.log(age);  // 20
</script>

4, Arrow function

() => {}

() contains formal parameters and {} contains function bodies
Usually we assign an arrow function to a variable

 <script>
    const fn = () => {
        console.log("123");
    }
    fn();  // 123
</script>

In the arrow function, if there is only one sentence of code in the function body and the execution result of the code is the return value of the function, the braces in the function body can be omitted

<script>
    const sum = (n1, n2) => n1 + n2;
    const result = sum(2, 3);
    console.log(result);  // 5
</script>

this in arrow function

The arrow function does not bind the this keyword. This in the arrow function points to the context this of the function definition position
That is, this points to where the arrow function is defined.

<script>
    const obj = { name: 'Zhang San' };
    function fn() {
        console.log(this);
        return () => {
            console.log(this);
        }
    }
    const resFn = fn.call(obj);
    resFn(); // {name: "Zhang San"}
             // {name: "Zhang San"}
</script>

5, Remaining parameters

The residual parameter syntax allows us to represent an indefinite number of parameters as an array

<script>
   	function sum(first, ...args) {
        console.log(first);  // 10
        console.log(args);  // [20, 30]
    }
    sum(10, 20, 30);
</script>

6, Extension operator

The extension operator can convert an array or object into a comma separated sequence of parameters

<script>
    let ary = [1, 2, 3];
    console.log(...ary);  // 1 2 3
</script>

Convert a pseudo array to a real array

<script>
    var divs = document.querySelectorAll("div");
    console.log(divs);  // NodeList(5) [div, div, div, div, div]
    var ary = [];
    ary.push(...divs);
    console.log(ary);  // (5) [div, div, div, div, div]
</script>

7, Extension method of Array

find()

Used to find the first qualified array member. If it is not found, it returns undefined

<script>
    let ary = [{
        id: 1,
        name: 'Zhang San'
    }, {
        id: 2,
        name: 'Li Si'
    }]
    let target = ary.find((item) => item.id == 2);
    console.log(target);
</script>

findIndex()

Used to find the position of the first qualified array member. If not found, - 1 is returned
The usage is the same as the find method

includes()

Indicates whether an array contains a given value and returns a Boolean value.

[1, 2, 3].includes(2) // true
[1, 2, 3].includes(4) // false

8, Extension method of String

Template string

Use backquotes to define

let name = `zhangsan`;

Variables can be parsed in the template string

<script>
    let name = `zhangsan`;
    let say = `wo shi ${name}`;
    console.log(say);  // wo shi zhangsan
</script>

Template string can wrap

<script>
let result = {
    name: "Zhang San",
    age: 20
}
let html = `
    <div>
        <span>${result.name}</span>    
        <span>${result.age}</span>
    </div>
`
console.log(html);
</script>

Functions can be called in the template string

<script>
    let result = {
        name: "Zhang San",
        age: 20
    }
    const sayHello = function () {
        return "hello";
    }
    let greet = `${sayHello()}${result.name}`;
    console.log(greet);  // hello
</script>

startsWith() and endsWith()

startsWith(): indicates whether the parameter string is at the head of the original string.
endsWith(): indicates whether the parameter string is at the end of the original string.

<script>
    let str = 'Hello world!';
    console.log(str.startsWith('H'));  // true
    console.log(str.endsWith('!'));  // true
</script>

repeat() method

The repeat method repeats the original string n times and returns a new string

<script>
    var x = 'x'.repeat(2);
    console.log(x);  // xx
</script>

9, Set data structure

A Set is similar to an array
Different from the array, the members are unique and have no duplicate values.

Set itself is a constructor used to generate a set data structure

const s = new Set();

The Set function can accept an array as a parameter for initialization.

<script>
    const set = new Set([1, 2, 3, 4, 5, 4]);
    console.log(set);  // {1, 2, 3, 4, 5}
</script>

Instance method of Set

  • add(value): adds a value and returns the Set structure itself
  • delete(value): deletes a value and returns a Boolean value indicating whether the deletion is successful
  • has(value): returns a Boolean value indicating whether the value is a member of Set
  • clear(): clear all members without return value
<script>
    const s = new Set();
    s.add(1).add(2);
    console.log(s);  // {1, 2}
    s.delete(1);
    console.log(s);  // {2}
    console.log(s.has(2));  // true
</script>

Traversal set

s.forEach(value => console.log(value));
<script>
    const s1 = new Set([1, 2, 3, 4, 5]);
    s1.forEach(value => console.log(value));  // 1 2 3 4 5
</script>

Topics: Javascript ECMAScript