---
# System prepended metadata

title: What is hoisting?
tags: [note, Javascript]

---

# What is hoisting?
###### tags: `Javascript` `note`

### 解說
[MDN 解說](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting)

> JavaScript **Hoisting** refers to the process whereby the interpreter appears to move the _declaration_ of functions, variables, or classes to the top of their scope, prior to execution of the code.

Hoisting 指的是解析器在執行程式之前將函數(Function)、變數(Variable)或類別(Class)**宣告**移到其範圍頂部的過程。

### 效果

var
```js
console.log(value); // undefined
var value = 20;
```

可以模擬成
```js
var value;
console.log(value);
value = 20;
```
---
function
```js
foo();

function foo(){
    console.log("hello world");
}
```

可以模擬成
```js
function foo(){
    console.log("hello world");
}

foo();
```
---

### 目的
變數的 Hoisting 主要是語言設計本身所產生的，所以開發中會盡量避免變數 Hoisting 的特性。
主要功用還是以 function 為主，為解決函式因為宣告順序不同而無法**互相調用**的問題。

函式互相調用
```js
function foo(){
    bar();
}

function bar(){
    foo();
}
```

### let、const 有沒有 Hoisting?
答案是，有，不過行為不太一樣。

跟 var 的區別在於，let、const Hoisting 後不會對變數進行初始化(不會預設為 `undefined`)，所以在宣告變數之前使用變數會觸發錯誤。

[MDN **let** and **const** hoisting](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting#let_and_const_hoisting)

重點
>Note that it is the order in which code is _executed_ that matters, not the order in which it is written in the source file. The code will succeed provided the line that initializes the variable is executed before any line that reads it.

### class 的 hoisting
class 的 hoisting 跟 let、const 類似，雖然都被往上提了，不過都沒有初始化。

```js
const p = new Rectangle(); // ReferenceError

class Rectangle {}
```

[MDN class hoisting](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting#class_hoisting)

### 參考連結
- [我知道你懂 hoisting，可是你了解到多深？](https://blog.techbridge.cc/2018/11/10/javascript-hoisting/)
- [JavaScript: 变量提升和函数提升](https://www.cnblogs.com/liuhe688/p/5891273.html)