JavaScript 1.2 นำเสนอ concept ของ function literals ซึ่งเป็นวิธีใหม่ในการกำหนดฟังก์ชัน Function literal คือ expression ที่กำหนด unnamed function (anonymous function)
ตัวอย่าง
<html>
<head>
<script>
<!--
var func = function(x, y) { return x * y };
function secondFunction() {
var result;
result = func(10, 20);
document.write(result);
}
//-->
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
Function Literal = Function Expression
// Named function expression
var factorial = function fact(n) {
return n <= 1 ? 1 : n * fact(n - 1); // เรียกตัวเองได้ด้วยชื่อ fact
};
// Anonymous function expression (arrow function ES6+)
const multiply = (x, y) => x * y;
// IIFE (Immediately Invoked Function Expression)
(function() {
console.log("Runs immediately!");
})();
Function Declaration vs Function Expression
| ลักษณะ | Function Declaration | Function Expression |
|---|---|---|
| Syntax | function name() {} | var name = function() {} |
| Hoisting | ทั้งฟังก์ชัน | แค่ตัวแปร (var) |
| Name | บังคับต้องมี | อาจไม่มี (anonymous) |
| Scope | Function-scoped | ขึ้นอยู่กับ var/let/const |
สมัยใหม่: ใช้ const + arrow function หรือ function expression แทน var