The difference between the var, let the three const

ES6 added two important keywords let and const , inadvertently pulls out a summary of the differences before the notes under three, for everyone to share today (Please indicate the wrong place).

A, let

We all know that javascript is not block-level scope, functions and global work only domain, but let's break this situation was born, effective (focus ring) within a block of code variables declared only let command is located in let.

  1.let is valid block, var is effective (the code) globally

  

if(true) {
    let a = '我';
    var b =  '你';
}
console.log("let" + a);  //报错:Uncaught ReferenceError: a is not defined
console.log("var" + b);

 The question is: when we want to print out the cycle 0-9 this 10-digit, early, we often make such a mistake (error example):

for ( var I = 0; I <10; I ++ ) { 
  the setTimeout ( function () { 
    the console.log (I); 
  }) 
} 
// Output ten 10

Var variables declared effective on a global scale, so that only a global variable i, so the timer in the global variables i i worth, each cycle is the same print i, so after the end of the cycle, this time i have 10. To solve this problem (Correct example):

        for (var i = 0; i < 10; i++) {
            (function(i) {
                     setTimeout(function(){
                    console.log(i);
                  })
            })(i)
        }

We implemented by the closure function, because function hail, every time you create there will be a space to store their own unique value. We will execute every time i values ​​for loop, passed to the closure function to create different, so each closure i-valued function in memory, it will not be the same, so that to achieve the results we want. Because let's block-level scope, we also can be achieved by:

for (let j = 0; j < 10; j++) {
  setTimeout(function(){
    console.log(j);
  })
}
// 输出 0123456789

  Variable lift 2.let does not exist, var variables exist to enhance the

console.log(a);  //ReferenceError: a is not defined
let a = "我";
 
console.log(b);  //undefined
var b = "你";

 Enhance the presence of variable with the var statement when the script started running, b already exists, but has no value, it will output undefined

  3.let can not be repeated statement, var can declare a variable multiple times

let a = a;
let a = b;
var b = c;
var b = d;
a  // Identifier 'a' has already been declared
b  // d

 

Two, const command

const declare a variable read-only, the statement is not allowed to change, once the declaration must be initialized, for ES6 clear that, if there is the code block or let const, these variables will block command statements from the beginning of the block to form a closed scope. The code blocks before it being given the variable declaration.

var a = "a"; if(true){ console.log(a); // ReferenceError: a is not defined const PI = "3.1415926"; }

Guess you like

Origin www.cnblogs.com/liangjh518/p/11357207.html