Hoisting เป็นเทคนิค JavaScript ที่ย้าย Variables และ Function Declarations ไปด้านบนของ Scope ก่อนเริ่ม Execute Code ภายใน Scope ไม่ว่าจะประกาศ Functions หรือ Variables ที่ไหน จะถูกย้ายไปบน Scope
สังเกตว่า Hoisting ย้ายแค่ Declaration ส่วน Assignment อยู่ที่เดิม
ตัวอย่าง
console.log(functionBelow("Hello")); function functionBelow(greet) { return `${greet} world`; } console.log(functionBelow("Hi"));
ผลลัพธ์
Hello world Hi world
สังเกตว่า Function Declaration อยู่หลังการเรียก แต่ยังเรียกได้ เพราะ Function Hoisting
ยังสังเกตว่าไม่ทำงานเมื่อ Assign Functions เหมือน Variables
console.log(functionBelow("Hello")); var functionBelow = function(greet) { return `${greet} world`; } console.log(functionBelow("Hi"));
จะ Fail ด้วย Error: functionBelow is not a function
ถ้าลบ var จะ Fail ด้วย Error: functionBelow is not defined
สังเกตว่าเมื่อประกาศด้วย var ถูก Hoisted เป็น Variable ใน Context แต่ยังคง Undefined นี่คือ Variable Hoisting เนื่องจาก Property นี้ Anonymous และ Arrow Functions ไม่เคย Hoisted ใน JavaScript