⚡ Function Types
เรียนรู้ Functions ทุกแบบที่ใช้ใน JavaScript และ TypeScript
🎯 การประกาศ Functions
// Function Declaration (มี hoisting)
function calculateArea(width, height) {
return width * height;
}
// สามารถเรียกใช้ก่อนประกาศได้
console.log(calculateArea(5, 10)); // 50
// Function Expression (ไม่มี hoisting)
const calculatePerimeter = function(width, height) {
return 2 * (width + height);
};
// Named Function Expression
const factorial = function fact(n) {
return n <= 1 ? 1 : n * fact(n - 1);
};
// การใช้งาน
calculateArea(5, 3); // 15
calculatePerimeter(5, 3); // 16
factorial(5); // 120// Arrow Function แบบสั้น
const add = (a, b) => a + b;
const square = x => x * x; // parameter เดียวไม่ต้องมีวงเล็บ
const greet = () => "Hello!"; // ไม่มี parameter
// Arrow Function แบบยาว
const processUser = (user) => {
const fullName = `${user.firstName} ${user.lastName}`;
const age = calculateAge(user.birthDate);
return { fullName, age };
};
// Arrow Function กับ Object Return
const createUser = (name, email) => ({
id: Date.now(),
name,
email,
createdAt: new Date()
});
// Arrow Function ใน Array Methods
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
const sum = numbers.reduce((acc, n) => acc + n, 0);
console.log(doubled); // [2, 4, 6, 8, 10]
console.log(evens); // [2, 4]
console.log(sum); // 15