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?

image-20221027004918334

why hoisting

  1. using functions before actual declaration
  2. 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?

  1. make it easier to avoid and catch errors: accessing variables before declaration is bad practise and should be avoided
  2. make const varibles actually work
posted @ 2022-10-27 00:53  kihyun  阅读(20)  评论(0编辑  收藏  举报