Understand var and let in JavaScript in 2 minutes

If you’re a JavaScript beginner, you might have a question: why there’re too much way to declare the variable: “var” declaration from ES5, “let” and “const” from ES6, we can easily know “const” is for constant value, but what’s the difference between “var” and “let”?

Chinese: 用 1 分鐘簡單地了解 — JavaScript中 var 與 let 的主要差別 & 一次說清楚 JavaScript 中宣告的各種提升行為

let/const: { block scope }
var: function(){

function scope

}

Global →Function → Block

Summary

  • They have different scope “var” is scoped in function, “let” is scoped in block.
  • Hoisting in “var”
  • Temporal Dead Zone in “let”

Scope

We cannot access variable `b` in L6, try to use `var` to declare variable.

What interesting is, L12 also get the ReferenceError , it’s similar as L6, we cannot access the variable out of scope.

Hoisting

var declaration has hoisting behavior, but let doesn’t.

In the L2–5, we can found that variable1 has been hoisted, so there’s no reference error be thrown out.

What the actual for L2–5:

(function(){
var variable1;
console.log(variable1); // undefined
variable1 = 20;
}())

Temporal Dead Zone

difference of repetitive declaration

L1–6, we cannot repetitive declare the same variable in same scope, that’s the TDZ for let.

But we can do that using var.

Conclusion

Just image that when you’re in elementary school, the classmate sit close to you always did that: “Hey, I mark a line between us, just don’t across that!”

Right, that’s the concept of scope, in your own place, even you two put the same math book, but you’ll not take the wrong one.

How the mess if scope is bigger?

You can ask your big brother/sister, how they allocate the properties like house, cars, etc. after getting married, lol.

If any interest, 👉 https://realdennis.me.