Functions
Functions
Section titled “Functions”Function Declaration vs Expression
Section titled “Function Declaration vs Expression”// Function Declaration — hoisted (ใช้ก่อนประกาศได้)function greet(name) { return `สวัสดี ${name}!`;}
// Function Expression — ไม่ hoistedconst greet2 = function(name) { return `สวัสดี ${name}!`;};
// Arrow Function — syntax สั้น (ES6+)const greet3 = (name) => `สวัสดี ${name}!`;def greet(name): return f"สวัสดี {name}!"
# lambda (arrow function equivalent)greet2 = lambda name: f"สวัสดี {name}!"char* greet(const char* name) { static char buf[100]; sprintf(buf, "Hello %s!", name); return buf;}-- SQL ใช้ stored functionCREATE FUNCTION greet(name VARCHAR(50))RETURNS VARCHAR(100) AS $$ SELECT 'สวัสดี ' || name || '!';$$ LANGUAGE sql;Arrow Functions แบบละเอียด
Section titled “Arrow Functions แบบละเอียด”// parameter เดียว — ไม่ต้องมีวงเล็บconst double = x => x * 2;
// หลาย parameters — ต้องมีวงเล็บconst add = (a, b) => a + b;
// ไม่มี parameter — ต้องมีวงเล็บเปล่าconst getRandom = () => Math.random();
// body หลายบรรทัด — ต้องมี {} และ returnconst calculate = (a, b) => { const sum = a + b; const avg = sum / 2; return avg;};
// return object — ต้องครอบด้วย ()const makeUser = (name, age) => ({ name, age });Default Parameters
Section titled “Default Parameters”function createUser(name, role = "viewer", active = true) { return { name, role, active };}
createUser("สมชาย"); // { name: "สมชาย", role: "viewer", active: true }createUser("สมหญิง", "admin"); // { name: "สมหญิง", role: "admin", active: true }createUser("วิชัย", "editor", false); // { name: "วิชัย", role: "editor", active: false }Rest Parameters (...)
Section titled “Rest Parameters (...)”// rest — รวม arguments ที่เหลือเป็น arrayfunction sum(...numbers) { return numbers.reduce((total, n) => total + n, 0);}
console.log(sum(1, 2, 3)); // 6console.log(sum(10, 20, 30, 40)); // 100
// rest ต้องอยู่ตัวสุดท้ายfunction log(level, ...messages) { console.log(`[${level}]`, ...messages);}Spread Operator (...)
Section titled “Spread Operator (...)”// spread arrayconst nums1 = [1, 2, 3];const nums2 = [4, 5, 6];const all = [...nums1, ...nums2]; // [1, 2, 3, 4, 5, 6]
// spread เป็น argumentsMath.max(...nums1); // 3
// spread objectconst defaults = { theme: "dark", lang: "th" };const settings = { ...defaults, lang: "en" }; // override lang