Understand var and let in JavaScript in 2 minutes

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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store