functionDisplayOne เป็น Function Expression ส่วน functionDisplayTwo เป็น Function Declaration ฟังก์ชัน declaration ถูกกำหนด (defined) ทันทีที่ surrounding function ถูก execute (hoisted)
ทั้งสองวิธีใช้ประกาศฟังก์ชันใน JavaScript และ functionDisplayOne เป็น anonymous function
Function Expression
functionDisplayOne(); // TypeError: functionDisplayOne is not a function (ยังไม่ได้ assign)
var functionDisplayOne = function() {
console.log("Hello!");
};
functionDisplayOne(); // "Hello!" - ทำงานได้หลัง assign
Function Declaration
functionDisplayTwo(); // "Hello!" - ทำงานได้! (hoisted ทั้งฟังก์ชัน)
function functionDisplayTwo() {
console.log("Hello!");
}
ความแตกต่างสำคัญ
| ลักษณะ | Function Declaration | Function Expression |
|---|---|---|
| Hoisting | ทั้งฟังก์ชัน (name + body) | แค่ตัวแปร (var hoisted, init = undefined) |
| Name | มีชื่อ (named) | อาจเป็น anonymous หรือ named |
| Scope | Function-scoped (var) | ขึ้นอยู่กับ var/let/const |
| ใน Block (ES6+) | ไม่แนะนำ (browser-dependent) | OK กับ let/const (block-scoped) |
Arrow Function (ES6+)
const fn = () => console.log("Hello!"); // Function expression (arrow)
// ไม่มี this, arguments, super, new.target ของตัวเอง
แนะนำ: ใช้ Function Expression (arrow/const) เพื่อความชัดเจนและหลีกเลี่ยง hoisting confusion