Usually the interview To talk about the var let const this 3 person the difference

Today we’ll talk about the difference

In the past, I’ve been saying pretty much anything that’s used to declare objects except that const is a little bit special and it can’t change the value of the object that it declares except for string and number array and obj

{
    let a = "let definde a";
    var b = "var definde b";
    const c = "const dedinde c";
}


console.log(a);  // a is not dedine
console.log(b);  // var definde b
console.log(c);  // c is not dedine
Copy the code

Let and const are not available outside the {} scope. Let and const are not available outside the declared scope

Most of the time, we pass

If (typeof a === 'undefined')Copy the code

But this can only happen if you use var to declare a variable because var will raise the variable

Declare a variable with var let const and print it above the declaration

console.log(a) var a = 1; console.log(a) let a = 1; console.log(a) const a = 1; - Undefined: Cannot access 'a' before initialization - Initialization: Cannot access 'a' before initializationCopy the code

In both let and const cases, the typeof variable is not available until the variable has been declared and undefined is meaningless

So a lot of times we have to change the way we write try{console.log(a); }catch(e){console.log("a does not exist ",e)} const a = 1; let a = 1;Copy the code

And then there’s the case of both

var b = 2; if(b){ b = 3; console.log(b); // Initialization: Cannot access 'a' before initialization let b = 1; console.log(b); //1 b = 3; console.log(b); / / 3}Copy the code

As long as a variable is declared in a block-level scope its scope is not affected by external declarations of the same variable and its scope is not accessible until it is declared in a temporary dead zone

And here’s the fun thing: in the for loop, I declare the variable index with let and in the loop I declare index again with let

Normally if you declare var a=1 in the same scope; var a=2; consloe.log(a); //2 But let the same declaration consloe.log(a); //Identifier 'a' has already been declared it will declare an error, warning that you have declared it but then the for loop will print 3 times for (let index = 0; index < 3; index++) { let index = "index"; console.log(index); // index index index }Copy the code

Here we can think of for as the parent scope. For (declared here to be parent) {declared here to be child} they both operate on two different scopes, so no errors are reported

Through these have to give you a silk in front of a bright