Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Function Hoisting trong JavaScript

Hoisting: JS di chuyển declaration của variable/function lên đầu scope trước khi chạy code. Bất kể khai báo ở đâu, đều được move lên top.

Lưu ý: Chỉ declaration được hoisted, assignment giữ nguyên chỗ.

Ví dụ: Function Declaration hoisted

console.log(functionBelow("Hello")); // Gọi trước khi khai báo
function functionBelow(greet) { return `${greet} world`; }
console.log(functionBelow("Hi"));

Kết quả

Hello world Hi world

Function declaration hoisted hoàn toàn (cả tên và body).

Function Expression KHÔNG hoisted

console.log(functionBelow("Hello")); // Error!
var functionBelow = function(greet) { return `${greet} world`; };
console.log(functionBelow("Hi"));

Lỗi: functionBelow is not a function (biến hoisted nhưng giá trị = undefined).

Bỏ var: functionBelow is not defined (ReferenceError).

Tóm tắt:

  • Function declaration: Hoisted hoàn toàn (có thể gọi trước khi khai báo)
  • var function expression: Biến hoisted (undefined), không gọi được
  • let/const function expression: Temporal Dead Zone, ReferenceError
  • Arrow function / Anonymous function: Không hoisted (là expression)
  • Class declaration: Không hoisted (phải khai báo trước khi dùng)