Detailed introduction to JS-ES6

let and const


Block level scope: a scope that is common in all languages;

      var a = 10;
      let b = 20;
     console.log(b)// b is not defined

Variables declared with let in a brace are not externally accessible, and each brace is an independent scope

With the let declaration, we cannot access i outside the function, and i only exists in the for loop as a subscript. Therefore, each i is independent at this time; We can easily get the subscript of the current element when clicking, without doing a lot of tedious processing

var aLi = document.querySelectorAll("li");
for(let i = 0;i<aLi.length;i++){
  aLi[i].onclick = function(){
  console.log(i);//0  1  2  3

In JS, a variable declared by var has declaration elevation, which is a defect in JS. However, the current let does not have declaration elevation

        // console.log(a);//undefined
        // console.log(b);//b is not defined
        // var a = 10;
        // let b = 20;
        let a = 20;
        function foo(){
            let a = 10;
        foo();//a is not defined
        //Error reporting, temporary dead zone
        //js found a local a during precompiling, so we won't look for the global a
        //However, during execution, he finds that the local a is declared by the following let, so an error is reported

ES6 specifies that in a block, once a variable is declared with let or const, the block will become a block level scope. The variable declared with let or const is bound to the block and is not affected by any variable. Cannot be used before the variable is declared with let. Grammatically, we call this a temporary dead zone (TDZ)

const constant

Declare constants:

const a = 20;//Constants: quantities that cannot be modified
a = 30;    
//Uncaught TypeError:Assignment to constant variable. (uncaught type error: assignment to constant variable)
        Math.PI = 4;
const arr = [2,3,4,5];
        //arr = [3,4,4,6];
        //You cannot modify the array or object reference, but you can modify the internal structure through the API
        console.log(arr);//[2, 3, 4, 5, 6, 7]

Extended operators

Three period signs. The function is to expand an array or array like object into a series of values separated by commas

var arr = [1,2,3,4,5];
        console.log(...arr);//1 2 3 4 5   console. The log does not display commas. In fact, there are commas in the middle
        function add(arr){
 var foo = function(a, b, c) {
var arr = [1, 2, 3];
//Traditional writing
foo(arr[0], arr[1], arr[2]);
//Use extended operators

rest operator

The rest operator is also a three dot operator, but its function is just the opposite to that of the extension operator. It combines a comma separated sequence of values into an array

 //It is mainly used for indefinite parameters, so ES6 can no longer use the arguments object
var bar = function(a, ...args) {
bar(1, 2, 3, 4);
//[ 2, 3, 4 ]

String extension (understand)

1. Unicode representation of string; The rule is \u + four hexadecimal digits;

 //For example: console log("\u0061");

The print result is a;

This new character representation can only represent numbers between \u 0000 and \u ffff. If it is out of range, it must be represented by double bytes;


The print result is_
If you are not familiar with writing according to the rules, such as console log("\uD842\uDFB69")
This 9 is an extra character; Then it is considered that this segment of characters is \D842uDFB6+9, so the print result is 9;

If we want to represent characters that are out of range at one time, we can use {} to represent them;
For example:
console.log("\u20BB9"); The print result of this is split ₻ 9
console.log("\u{20BB9}"); The result of this print is a complete character

ES6 supports character representation in multiple formats;

String template extension:

There is a new string in ES6, which is represented by (the character on the wavy line > backquote);

Usually, we want to splice a string with a label in this way:

      bianliang + " <strong>This is a word" + + "</strong> " + bianliang

But with ES6 strings, everything becomes very simple;

      `  ${bianliang} <strong>This is a word ${}</strong>${bianliang} `

Expanding variables with ${} makes splicing very easy;
Very simple line feed;

      `In JavaScript \n is a line-feed.`     
      console.log(`string text line 1
      string text line 2`);

When we want to use 'backquotes' in a string, we need to escape;

      `\`Yo\` World!`    //"`Yo` World!"

Templates can also call functions;

      function fn() {
      return "Hello World";
      `foo ${fn()} bar`

New method of string:

repeat() repeat function

 'x'.repeat(3)  //xxx;
  Duplicate string;

includes() startsWith() endsWith();

Determine whether a string exists in the string;

var s = 'Hello world!';

s.startsWith('Hello') // true starts with a parameter

s.endsWith('!') // true ends with a parameter

s.includes('o') // true includes parameters;

The second method accepts the second parameter, and the second parameter indicates the starting position;

  var s = 'Hello world!';

  s.startsWith('world', 6) // true

  s.endsWith('Hello', 5) // true

  s.includes('Hello', 6) // false

for of

A new traversal method;
for of can be used to traverse strings:

      var s = "abc";
      for(let  b of s){
           console.log(b) // "a"  "b"  "c"

=>Arrow function

var test = function(x){
    return x+2;

Use the arrow function: VAR test = x = >x+2;
var function name = parameter = > operation rule;

If the arrow function has only one formal parameter, you can omit the parentheses

    var foo = str => {

If the function body has only one sentence, you can omit the braces

    var foo = str => console.log(str);

If there is only one sentence and the sentence is return, you can omit the return keyword

var foo = str => str+"abc";

The arrow function will automatically bind this (the arrow function does not have its own this)

document.querySelector("button").onclick = function(){
                setTimeout(() => {


First: the arrow function cannot be new. Its original design intention is different from that of the constructor
Second: if the arrow function wants to return a JSON object, it must be enclosed in parentheses var test = () = > ({id:3, val=20})

Destructuring assignment

var obj = {name:"lisi", age:80, gender: "female"};
            var {age, name, gender="male"} = obj;
            console.log(age, name, gender); 
var json = [
    {name:"lisi", age:80, gender: "female"},
    {name:"liwu", age:70, gender: "male"},
    {name:"liliu", age:60, gender: "female"}
var [{age},{name},{gender}] = json;
    //var {name} = b;

Symbol type the sixth basic data type symbol

The Symbol function generates a unique value. It can be understood that the Symbol type is close to the string, but the unique value is generated every time, that is, it is not equal every time. As for how much it is equal, it does not matter. This is useful for some dictionary variables

var s1 = Symbol();
var s2 = Symbol();
var s3 = Symbol("abc");
var s4 = Symbol("abc");

s1 Not equal to s2
s3 Not equal to s4

Case of using Symbol type: click div to change color

var obj ={
                red: Symbol(),
                blue: Symbol(),
                green: Symbol(),
                yellow: Symbol()
            var color =;
            //Applicable to the only concerned state (to which state)
            //But don't know the internal structure (don't care about the value)
            document.querySelector("div").onclick = function(){
                if(color ==={
           = "blue";
                    color =;
                }else if(color ==={
           = "green";
                    color =;
                }else if(color ==={
           = "yellow";
                    color = obj.yellow;
                }else if(color === obj.yellow){
           = "red";
                    color =;

Set and Map structures


The Set set is de duplicated by default, but the premise is that the two added elements are strictly equal, so 5 and "5" are not equal, and the strings from two new are not equal

A Set is essentially a wrapper around an array. For example:

 let imgs = new Set();
imgs.add(new String("abc"));
imgs.add(new String("abc"));
// Printed results: 15'5''abc''abc'

The following shows a very sophisticated method of array de duplication

var newarr = [ Set(array)];

Set set traversal:

1. traverse according to KEY

 var imgs = new Set(['a','b','c']); 
 //Traverse by KEY
for(let item of imgs.keys()){
} //a //b //c

2. traverse according to VALUE

 //Traversal by VALUE
for(let item of imgs.values()){
} //a //b //c

3. traverse according to KEY-VALUE

for(let item of imgs.entries()){
 } //['a','a'] //['b','b'] //['c','c']

4. normal for... of loop

 //Normal for Of loop (the difference between for...of and for in is obvious, that is, the direct value is obtained instead of the subscript)
for(let item of imgs){  
} //a //b //c


Map set, i.e. map

 let map = new Map();
map.set("S230", "Zhang San");
map.set("S231", "Lisi");
map.set("S232", "Wang Wu");
map.get("s232"); // Get an element king five
for(let [key,value] of map)
 //Loop traversal with deconstruction assignment 

class in French (understand)

Class reserved word finally becomes keyword
Previously wrote a constructor (class)

function Pad(color){
    this.color = color;

Now the writing method is closer to Java

class Iphone{
    constructor(color, size){
            this.color = color;
            this.size = size;    
          return `The color of this phone is ${this.color} Screen size is ${this.size}`;

We define a class named Iphone, and generate an instance through the class: var iphone = new Iphone("white", 5);

The constructor is called the constructor. When we create a new object, it is automatically called

However, in essence, JS is still implemented using prototypes. That is to say, this is just a new writing method, which is no different from the previous constructor.

Note that class is used to define a class, which must be defined before use

Tags: Javascript ECMAScript

Posted by bryanptcs on Thu, 11 Aug 2022 22:41:03 +0530