ES6 learn the let and const commands in Chapter 1

Time:2022-6-8

preface:

Recently started watchingIntroduction to ECMAScript 6 by Ruan Yifeng(hereinafter referred to as the original text) learn the knowledge of ECMAScript 6 (hereinafter referred to as ES6), sort out some knowledge points and add my understanding to make article notes. Each chapter is divided into one note.
The article code is different from the directory structure and the original text.

Link to the original text of this chapterLet and const commands

let

letIs used to declare avariable
Different fromvarThere will be variable escalation (described below),letThe declared variable value only exists in theletThe command is valid within the code block.
The same scope (described below) cannot be usedletDeclare the same variable repeatedly.

be careful

  • Declare variables
  • No variable promotion
  • Non repeatable declaration
  • Only inletThe code block where the command is located is valid
let sample = 1;
sample = 2;
let sample = 2; //  An error will be reported
{
  let sample = 1;
  console. log(sample); //  Normal output 1
}

console. log(sample); //  An error will be reported because it is only valid in the code block where the let command is located

const

constIs used to declare aRead only constant
Once declared, the value of the constant cannot be changed. If you try to change the value of a constant, an error will be reported.
alsoconstYou must assign a value to it when you declare it. If you only declare that it does not assign a value, an error will be reported.
The same scope is not availableconstThe same constant is declared repeatedly.
constAndletThe same can only be valid in the code block because of the scope.

Const actually guarantees that the data stored at the memory address pointed to by the variable cannot be changed, not the value of the variable.

be careful

  • declare constant
  • Cannot be changed after declaration
  • Must be assigned when declaring
  • Non repeatable declaration
  • stayconstThe code block where the command is located is valid
const sample = 1;
sample = 2; //  An error will be reported, and the variable declared by const cannot be re assigned
const sample; //  An error is reported directly. When const is declared, it must be assigned a value

Let and Const

introduceletAfter, it can be replacedvarYes, atletAndconstMiddle usableconstJust tryconst

Differences between let and Const

letAndconstThe difference between a declared variable and a declared constant is that a variable can be re assigned and a constant cannot be re assigned.

let sampleLet = 2;
const sampleConst = 1;

sampleLet = 3; //  normal
sampleConst = 3; //  report errors

Let is the same as const

  • Can only be declared before being used. Variable promotion is not allowed.
  • Cannot be declared repeatedly in the same scope
  • Are only valid in the code block where the command is located
{
sampleLet; //  report errors
sampleConst; //  report errors
  
let sampleLet = 2;
const sampleConst = 1;
  
let sampleLet = 3; //  report errors
const sampleConst = 3; //  report errors
}

sampleLet; //  report errors
sampleConst; //  report errors

Variable lifting

Before ES6, usevarDeclaring variables produces a feature called variable promotion.
No matter where the code is declared, it will be promoted to the top of the current scope. This behavior is called variable promotion.
In order to correct this phenomenon,letThe command changes the syntax behavior. The declared variables must be used after the declaration, or an error will be reported

AboveletAndconstIndicates that variables cannot be promoted. Is that true?
In fact, in JavaScript, all representationsvar, let, const, function, function*, classWill be promoted.
letAndconstDeclared variables will be created when the environment is instantiated, but they are not allowed to be accessed in any way before the lexical binding of variables, that is, when you call variables before declaration, an error will be reported, but the error information is not undefined but cannot be accessed before initialization. This leads to the next concept calledTemporary deadband

//The VaR declaration will promote the variable and no error will be reported, but the value is undefined
console.log(sampleVar); // undefined
var sampleVar = 1;

//Let declares that it will not promote variables, but the error is not defined
console.log(sampleLet); // Cannot access 'sampleLet' before initialization
let sampleLet = 1;

//Const declaration does not promote variables, but the error is not defined
console.log(sampleConst); // Cannot access 'sampleConst' before initialization
const sampleConst = 1;

//If you directly use an undeclared variable, the error is "is not defined“
console.log(sample); //sample is not defined

Temporary deadband

ES6 specifies that if there areletandconstFor variables declared by the command, this block forms a closed scope for these variables from the beginning. If these variables are used before declaration, an error will be reported. These variables cannot be accessed (obtained or set) until the declaration statement is completed,
This is called grammatically“Temporary deadband”(temporary dead zone, short TDZ), that is, the area from the beginning of the code block to the completion of the variable declaration statement.

var sample = 1;
if (true) {
  sample = '1';  //  report errors
  let sample;
}

Simply put, it’sletandconstThe variables declared by the command already exist when they enter the scope of the declaration code, but they cannot be obtained or used until the declaration statement is completed.

Block level scope

Scope is the accessible scope of variables and functions, that is, scope controls the visibility and life cycle of variables and functions.

Let and const block level scopes

Scope is not a new thing in ES6, but in Es5, there are only global scope and function scope. To solve the block level scope,ES6 can be used**let**And**const**Declare a variable with a block level scope.
varThe declared variables have the variable promotion feature, so there is no block concept. They can be accessed across blocks, but not across functions.
The outer scope cannot read variables from the inner scope.

{// block scope
  var sampleVar = 1;
  let sampleLet = 2;
  const sampleConst = 3;
  console. log(sampleVar); //  Successful output 1
  console. log(sampleLet); //  Successful output 2
  console. log(sampleConst); //  Successful output 3
}
console. log(sampleVar); //  Successful output 1
console. log(sampleLet); //  Error not defined
console. log(sampleConst); //  Error not defined

ES6 allows arbitrary nesting of block level scopes.
The same scope is not availableletorconstDeclare the same variable,An inner scope can define a variable with the same name as an outer scope.

{
  {
    {
      let sample = 'Hello World'; //  Outer scope
      { let sample = 'sample'; } //  No error
      { console.log(sample); }  //  Normal output 'hello world'
    }
  }
}

Block level scope and function declaration

Es5 specifies that functions can only be declared in the top-level scope and function scope, not in the block level scope.
ES6 specifies that in a block level scope, the behavior of a function declaration statement is similar to**let**, which cannot be referenced outside the block level scope.

/* 
    Es5, both of these cases are illegal because the two function declarations are declared in the block scope.
  However, in order to be compatible with the previous old code, the browser should support declaring functions in the block level scope. So no error will be reported
*/ 

if (true) {
  function sampleFn() {}
}

try {
  function sampleFn() {}
} catch(e) {
  // ...
}
/* 
    ES6, the behavior of the function declaration statement is similar to that of a let, and it cannot be referenced outside the block level scope
*/ 

if (true) {
  sampleFn();  //  Normal output, function declaration statements behave like lets
  function sampleFn() {
    console.log('Hello World');
  }
}

//However, functions can also be referenced outside the block level scope, but the value is undefined

if (false) {
  function sampleFn() { console.log('Hello World'); }
}
console. log(sampleFn); //  Normal output undefined
sampleFn(); //  The error is samplefddddn is not defined

Why can functions be referenced outside the block level scope?
If you change the processing rules of the functions declared in the block level scope, it will obviously have a great impact on the old code. In order to reduce the incompatibility caused thereby, ES6 is specified in Appendix B,The implementation of the browser may not comply with the above provisions(refers to the behavior of a function declaration statement), which has its own behavior.

  • Allows functions to be declared within a block level scope.
  • Function declarations are similar to**var**, which is promoted to the header of the global scope or function scope.
  • At the same time, the function declaration is promoted to the head of the block level scope.

be carefulThe above three rules are only valid for the browser implementation of ES6, and other environment implementations do not need to follow them. Instead, the function declaration of the block level scope is treated aslethandle.

We should avoid declaring functions within a block level scope. If necessary, it should also be written as a function expression instead of a function declaration statement.

//Function declaration statements should not be used in the block scope because there will be variable promotion
{
  function sampleFn() {
    console.log("Hello World");
  }
}

//Function expression. In the block scope, the function will not have variable promotion
{ 
  const sampleFn = function () {
    console.log("Hello World");
  }
}

Top level object

The top-level object, in the browser environment, refers towindowObject.
In Es5, the attributes of top-level objects are equivalent to global variables.
ES6 in order to change this,
On the one hand, in order to maintain compatibility,varCommands andfunctionThe global variable declared by the command is still the attribute of the top-level object;
On the other hand,letCommandconstCommandclassThe global variable declared by the command does not belong to the property of the top-level object.

/*
    In Es5, the attribute assignment of the top-level object is the same as that of the global variable.
*/

window.sample = 1;
console. log(window.sample); //  Normal output 1
sample = 2;
console. log(window.sample);//  Normal output 2

/*
    In ES6, the global variables declared by the let command, const command and class command do not belong to the attributes of the top-level object.
*/

var sampleVar = 1;
console. Log (window.samplevar) // normal output 1
let sampleLet = 1;
console. Log (window.samplelet) // output undefined normally
let sampleConst = 1;
console. Log (window.sampleconst) // output undefined normally

windowProvides a global environment (that is, a global scope) in which all code runs.

In the functionthisIf a function is not run as a method of an object, but simply as a function,thisPoints to the top-level object. However, in strict mode, whenthisWill returnundefined
Whether in strict mode or normal mode,new Function('return this')(), the global object is always returned.

function sampleFn(){
  console.log(this);
}
sampleFn(); //  Normal output output global object window

function sampleFn1(){
  "use strict";
  console.log(this)
}
sampleFn1(); //  Normal output undefined

//Turn on strict mode
"use strict";
const sample  = new Function('return this')();
console. log(sample); //  Normal output output global object window

Recommended Today

A front-end developer's Vim is the same as an IDE

Here is my new configurationjaywcjlove/vim-webI've been grinding it, and it's basically ready to use. Take it out and cheat the star Install The latest version of Vim 7.4+ uses (brew install macvim) installation, vim version updatebrew install macvim –override-system-vim View configuration locations # Enter vim and enter the following characters :echo $MYVIMRC download vim-web Download […]