JavaScript works behind the scenes —— hoisting and TDZ(变量提升和暂时性死区)
JavaScript works behind the scenes —— hoisting and TDZ(变量提升和暂时性死区)
concept
Makes some types of variables accessible/usable in the code before they are actually declared. "Variables lifted to the top of their scope"
(让某些类型的变量可以在他们被真正声明之前就可以使用,将他们提升到最高层的作用域)
how to hoisting?
why hoisting
- using functions before actual declaration
- var hoisting is just a byproduct
TDZ(Temporal dead zone)(暂时性死区)
变量用let/const声明之前就调用,那时不可用,在声明之前的scope成为暂时性死区。
example:
console.log(`Hello ${name}`)
let name = 'kihyun'
throw error: Reference Error: Cannot access 'name' before initialization
why TDZ?
- make it easier to avoid and catch errors: accessing variables before declaration is bad practise and should be avoided
- make const varibles actually work