preface

Var, let, const I’m sure you use it a lot, but there’s a lot to be said between them. I just stepped in a hole a while back, so I’ll write that down.

The same

  1. Var, let, and const can all be used to declare variables
var a = 1
const b = []
let c = 's'
Copy the code

This is what we usually use, but if that’s all there is to it, why invent 3 keywords to declare variables, so we need to talk about their differences

The difference between

  1. varThe variable defined can be variable promoted, whileletandconstDefined variables do not
console.log(a)
console.log(b)
console.log(c)
var a = 1
let b = 2
const c = 3
Copy the code

We know that variable promotion allows us to declare a variable before it is defined, so the first line should print undefined (only declare unassigned). But b and C are not defined by var so the second line and the third line are going to raise ReferenceError

  1. varDeclared variables can be redeclared and reassigned. butletDeclared variables cannot be redeclared in the same block of scope.constA declared variable cannot be redeclared or assigned in the same scope. We call it a constant, and you can test it yourself
  2. A concept called block-level scope was mentioned above. It wasn’t there before, but block-level scopes were added after ES6 becauseletandconstDeclared variables can only be accessed at the block level scope. What is block-level scope? by{}The area enclosed by curly braces is a block-level scope, and this is where I mentioned the pit I stepped on in my previous project
if(true) {const a = 1
 }
alert(a)
Copy the code

Given the knowledge above, it is obvious that this will give an error because the a variable can only be accessed in the if block-level scope. We can change it to var and we’ll be fine. To this small knowledge too not care, the lower the more easy to step on, I hope we take warning!!