Introduction to new features of JavaScript ES6

Posted by jomofee on Tue, 22 Feb 2022 01:53:14 +0100

brief introduction

The full name of ES is ECMAScript, which is the specification of scripting language, and JavaScript is an implementation of ES, so the new feature of ES can also be called the new feature of JavaScript.

Why learn:

  • Simple grammar and rich functions.
  • Using the framework to develop applications, such as front-end development using Vue, requires a lot of ES6 knowledge.

Why specialize in ES6:

  • ES6 has the most changes in the ES version and is of milestone significance.
  • ES6 adds many new syntax features, which makes the programming easier and more efficient.

Feature 1: let keyword

let keyword is used to declare variables, similar to var, but it has some special features.

  • Variables declared with let cannot be declared repeatedly:

    result:


result:

  • Block level functions on var. there is no scope, that is, variables declared in block level can be used in global and other code blocks, but let cannot. Code blocks refer to if, else, if, else, for, while, etc

    result:

  • There is no variable promotion, which means that the variable must be used after the variable declaration.
    var effect:

Result: the variable declared by var can be used before the variable declaration, but there is no assignment undefined.

let effect:

result:

const keyword

const keyword is used to declare constants, that is, it must be assigned at the time of declaration, and can no longer be changed.

result:

Cannot change:


Immutability here means that if it is a basic type, its value cannot be modified. For example, in the above example, if it is a replacement of an object or array, the reference of the object or array cannot be modified, but its elements can be modified.


result:

Internal elements can be modified:

  • Block level scope, the same as let.

const is generally used to declare objects and let is used to declare basic data types.

Destructuring assignment

ES6 allows you to extract values from arrays or objects according to a certain pattern and assign values to variables, which is called deconstruction assignment.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Destructuring assignment </title>
</head>
<body>
    <script>
        //Deconstruction of array
        const arr = [1,2,3,4];
        let [one,two,three,four] = arr;
        console.log(one);
        console.log(two);
        console.log(three);
        console.log(four);

        //Deconstruction of objects
        const obj = {
            name:"yehaocong",
            sex:"male",
            age:25,
            fun:function() {
                console.log("Ha ha ha");
            }
        };

        //The deconstructed attribute name should correspond to that in obj
        let {name,sex,age,fun} = obj;
        console.log(name);
        console.log(sex);
        console.log(age);
        console.log(fun);
        fun();

    </script>
</body>
</html>

result:

How to declare a string``

Strings can be declared in double quotation marks and single quotation marks.
ES6 adds a ` `,
The feature is that it can wrap and splice in a slightly different way:
When using double quotation marks or single quotation marks to define a string, line feed will report an error.

result:

No error will be reported when using the new method:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>String declaration</title>
</head>
<body>
    <script>
        let strNew = `
            <ul>
                <li></li>    
                <li></li>   
                <li></li>   
            </ul>
        `;
        
        console.log(strNew);
        //Splicing
        let strNew3 = "<div>" + strNew + "</div>";
        let strNew4 = `<div>${strNew}<div>`;
        console.log(strNew3);
        console.log(strNew4);
    </script>
</body>
</html>

Optimization of object attribute definition

ES when defining object attributes, if the string of the variable corresponding to the attribute name and attribute value is the same, the attribute value can be omitted.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Optimization of object attribute definition</title>
</head>
<body>
    <script>
        let name = "yehaocong";
        let age = 18;

        function fun() {
            console.log("aaaa");
        }

        const obj = {
            name,
            age,
            fun
        };
        console.log(obj);
    </script>
</body>
</html>

Arrow function

ES adds a new syntax for defining functions, arrow functions.

Other features are in this Code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Arrow function</title>
</head>
<body>
    <script>
        /**
         * The specific syntax is (parameter list, if there is only one parameter, parentheses can be omitted) = > {code logic. If there is only one line of code, curly braces can be omitted, and the value of this line of code will be used as the return value of the function}
         * 
         */ 
        let fun1 = ()=>{
            console.log("fun1");
        };
        fun1();

        let fun2 = param => param*2;
        console.log(fun2(1));

        console.log("separate================");

        /**
         * this If the ordinary function definition method is used, this is the context of its function definition.
         * If you use the arrow function, this will always point to the value of this in the current scope. In other words, the arrow function does not have its own this. To find this in the current scope, you can't change it by using call and apply
         */

         //this of the current global scope is Window
         console.log("Currently acting on this=",this);

         //First verify that call and apply cannot change this.
         console.log("Verify first call and apply It cannot be changed this================================");
         let fun3 = function(){
             console.log("Ordinary function this=",this);
         }

         let fun4 = ()=>{
             console.log("Arrow function this=",this);
         }

         const obj = {
             name:"yehaocong",
             age:25
         }

         fun3.call(obj);
         fun3.apply(obj);
         fun4.call(obj);
         fun4.apply(obj);

         //Verify that the value of this is different
        console.log("verification this Different values of================================");
        let obj2 = {
            name:"yehaocong",


            fun1:function(){
                //The setTimeout delayer is defined in the context of window, so when using an ordinary function as a callback, this of the function is window
                setTimeout(function() {
                //The callback function of the delayer set here uses ordinary functions
                console.log("object obj The callback function when using the delayer uses the ordinary function this Value of=",this);
            }, 1000);
            },

            
            fun2:function(){
                 //If the arrow function is used as a callback, this of the function always points to this of the current scope. In other words, the arrow function does not have this, so look up for this.
                 //Looking up this is this of function fun2, that is obj2
                setTimeout(() => {
                 //The callback function of the delayer set here uses the arrow function
                console.log("object obj The callback function when using the delayer uses the arrow function this Value of=",this);
            }, 1000);
            }
        };
        obj2.fun1();
        obj2.fun2();

        // //Arrow functions cannot be used as constructors
        // let fun5 = ()=>{

        // }
        // let fun5Obj = new fun5();
    
         
    </script>
</body>
</html>

Results: with the code, comments, careful taste will be a great harvest.

Arrow functions cannot be used as constructors:

result:

The arrow function has no argument list attribute argument:

result:

ES6 allows you to assign default values to function parameters

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Assign default values to function parameters</title>
</head>
<body>
    <script>
        //ES6 allows you to assign default values to function parameters. When the function is not called and the corresponding arguments are not passed, the default values will be assigned
        //grammar
        let fun1 = function(a,b=10){
            return a + b;
        }

        console.log(fun1(5,15));
        //The second parameter has no value, so the default value is 10
        console.log(fun1(5));
    </script>
    
</body>
</html>

result:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Assign default values to function parameters</title>
</head>
<body>
    <script>
       
         //Formal parameters requiring default values are generally set at the end of the formal parameter list. If you violate this, although there will be no error, it will be meaningless
         let fun2 = function(a,b=10,c){
            console.log(a);
            console.log(b);
            console.log(c);
        }
        fun2(1,2);
    </script>
    
</body>
</html>

Result: so it is generally used at the end.

If multiple parameters need default values, it's best to use them together with deconstruction, and put the deconstruction formal parameters last:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Assign default values to function parameters</title>
</head>
<body>
    <script>
      
        let fun3 = function(a,{name="1234",age,sex="male"}){
            console.log(a);
            console.log(name);
            console.log(age);
            console.log(sex);
        }

        fun3(1,{
            age:18,
            sex:"female"
        })
    </script>
    
</body>
</html>

result:

Variable parameter

ES6 introduces the variable parameter rest to replace the arguments parameter list.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Variable parameter rest</title>
</head>
<body>
    
    <script>
        //Using arguments
        let fun1 = function(a,b){
            console.log(a);
            console.log(b);
            console.log(arguments);
        }
        fun1(1,2,3,4);

        //Use variable parameter syntax:
        // ... Parameter name
        // The parameter must be placed last in the parameter list
        let fun2 = function(a,b,...param){
            console.log(a);
            console.log(b);
            console.log(param);
        }
        fun2(1,2,3,4,5,6);

    </script>
    
</body>
</html>

result:

The differences between arguments and rest are:

  1. arguments is the parameter of invisible injection, and rest is the parameter of explicit definition.
  2. arguments is an array of classes, which is actually an object, and rest is an array.
  3. The value of arguments covers all formal parameters, while rest will not cover the formal parameters defined above. If the figure shows that arguments covers a and b formal parameters, but rest does not.

If the variable parameter is not the last one, an error will be reported

Extended operator

Extended run character... Can convert an array into a comma separated list.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Extension operator...</title>
</head>
<body>
    
    <script>
        let arr = [1,2,3,4];
        let fun1 = function(){
            console.log(arguments);
        }
        //It is equivalent to splitting the array into 1,2,3,4
        fun1(...arr);

         This is equivalent to calling 
        fun1(arr[0],arr[1],arr[2],arr[3]);

        //Other uses


        console.log("Array merge============================");
        //Merging of arrays
        let arr1 = [1,2,3,4];
        let arr2 = [5,6,7];
        //Consolidation method 1
        console.log(arr1.concat(arr2));
        console.log([...arr1,...arr2]);


        console.log("Array cloning============================");
        //Cloning of arrays
        //This method is just a copy of the reference. The actual two variables still point to the same array
        let arr3 = arr1;
        console.log(arr3)
        //Print true
        console.log(arr3===arr1);

        //This is equivalent to creating a new array arr4, and then push ing arr1 into arr4
        let arr4 = [...arr1];
        console.log(arr4)
        //Print false
        console.log(arr4===arr1);

        //Convert a pseudo array into a real array, and arguments is a pseudo array
        console.log("Convert pseudo arrays to real arrays============================");
        let fun2 = function(){
            console.log(arguments);
            console.log("arguments Is it an array:",Array.isArray(arguments));

            //conversion
            let arr = [...arguments];
            console.log(arr);
            console.log("arr Is it an array:",Array.isArray(arr));
        }
        fun2(1,2,3);

        

    </script>
</body>
</html>

result:

Set constructor

ES6 adds a built-in constructor Set, which represents a collection, similar to an array, but its elements are unique and duplicate elements are not allowed.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Set aggregate</title>
</head>
<body>
    <script>
        //Constructor can pass in an array for initialization
        let setObj = new Set([8,9,10,10]);
        //There are four main APIs
        //newly added
        setObj.add(1);
        setObj.add(8)
        console.log(setObj);
        //delete
        setObj.delete(8);
        console.log(setObj);
        //Number of elements
        console.log(setObj.size);
        //Determine whether there is an element
        console.log(setObj.has(9));
        console.log(setObj.has(8));

        //Purpose:
        //Array de duplication
        console.log("Array de duplication===================================");
        let arr = [8,9,10,10,2,2,4,4];
        let set1 = new Set(arr);
        let arrNoRepeat = [...set1];
        console.log(arrNoRepeat);

        //intersect 
        console.log("intersect ===================================");
        let set2 = new Set([1,2,3]);
        let set3 = new Set([2,3,4,5]);
        let andSet = [...set2].filter(item => set3.has(item));
        console.log(andSet);

        console.log("Union set===================================");
        let set4 = new Set([1,2,3]);
        let set5 = new Set([2,3,4,5]);
        let setOr = [...new Set([...set4,...set5])];
        console.log(setOr);

        //The subtraction set is the opposite of the intersection set
        console.log("Take difference set===================================");
        let set6 = new Set([1,2,3]);
        let set7 = new Set([2,3,4,5]);
        let diffSet = [...set6].filter(item => !(set7.has(item)));
        console.log(diffSet);

    </script>
</body>
</html>

result:

Map structure

ES6 provides a Map structure, similar to an object, which is a collection of key value pairs, but the range of keys is not limited to strings. Various types and even objects can be used as keys.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Map</title>
</head>
<body>
    <script>
        let map = new Map();
        //set up
        map.set("name","yehaocong");
        console.log(map);

        //Get value according to key
        console.log(map.get("name"));

        //Get the number of map elements
        console.log(map.size);
        //Determine whether the key exists
        console.log(map.has("name"));
        console.log(map.has("yehaocong"));

        //Get key collection
        console.log(map.keys());
        //Gets the collection of values
        console.log(map.values());
        //Gets the collection of key value pairs
        console.log(map.entries());

        //Traversal, each item is an array, the element of subscript 0 is key, and 1 is value
        for(item of map){
            console.log(item);
        }
        
        //empty
        map.clear();
        console.log(map);
    </script>
</body>
</html>

result:

Number method extension

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Number Method extension</title>
</head>
<body>
    <script>
        //The new attribute indicates the minimum precision of JavaScript. When the subtraction of two numbers is less than this precision
        console.log(Number.EPSILON);

        //Determine whether it is a finite number
        console.log(Number.isFinite(200));

        //Judge whether it is NaN
        console.log(Number.isNaN(Number.parseInt("sad")));

        //Determine whether it is an integer
        console.log(Number.isInteger(12.23));

        //Truncate the decimal part, that is, round down
        console.log(Math.trunc(123.45));
    </script>
</body>
</html>

Front end interview questions of front-line large factories + development and learning notes + video explaining the latest architecture + handout of event station project
[ https://docs.qq.com/doc/DQVJzbnRIWWNtcVR4 ]Full content open source sharing

Topics: Javascript Front-end Vue.js html Interview