Functions of ES6 +: discrimination of VaR, let and const keywords

Time:2021-8-18

Discrimination of VaR, let and const keywords
var

  1. Variables with the same name can be defined repeatedly
var name='Bob';
var name='Tom';
console.log(name) //Tom 
  1. Variable promotion exists
//JavaScript can promote variables 
a = 2
console.log(a); //2 
var a
//However, initialized variables cannot be promoted
console.log(b); //undefined
var b=3;
  1. No block level scope
let arr=[];
for(var i=0;i<2;i++){
  arr[i]=function(){
    console.log(i)
  }
}
arr[0](); //2
arr[1](); //2
//VAR has no block level scope, I is a global variable, and because function is not called immediately, the loop will soon come to an end

let

  1. With block level scope
let arr=[];
for(let i=0;i<2;i++){
  arr[i]=function(){
    console.log(i)
  }
}
arr[0](); //0
arr[1](); //1
//If it is VaR, the result is 2. 2. Because VAR has no block level scope, I is a global variable, and function is not called immediately, the loop will soon come to an end
  1. There is a temporary deadband
let b=10;
function fn(){
  console.log(b);
  let b=20
}
fn(); 
//An error cannot access' B 'before initialization will be reported
  1. There is no variable promotion
x=3;
console.log(x); // An error cannot access' B 'before initialization will be reported
let x;
  1. Variables with the same name cannot be defined repeatedly
let name='Bob';
let name='Tom';
console.log(name) 
//The error identifier 'name' has already been declared will be reported

const

  1. With block level scope
if(true){
  const num=10;
}
Console.log (Num) // an error num is undefined will be reported
  1. Declared variables are read-only and require assignment
const PI 
Console.log (PI) // an error is reported: missing initializer in const declaration
const P=3.1415;
p=3;
Console.log (P) // an error assignment to constant variable. Will be reported
  1. If you declare a reference type (complex type data), the content can be modified, but the address cannot be modified
const obj = 
      {
        name: 'xm',
        age: 23
      }  
obj.age = 24;
console.log(obj); //  Can operate
obj = {}; // If you want to modify the address, you will report an error
console.log(obj);