Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

Fat Arrow Functions ใน JavaScript: Block Body และ Explicit Return


Fat Arrow Function (Block Body) ใช้ Curly Braces {} ครอบ Function Body ต้องใช้ return โดยตรง (Explicit Return) เหมาะสำหรับ Logic ที่ซับซ้อน หลาย Statement หรือมี Side Effects

Syntax

// พารามิเตอร์หลายตัว
const add = (a, b) => {
  return a + b;
};

// พารามิเตอร์เดียว
const double = (x) => {
  return x * 2;
};

// ไม่มีพารามิเตอร์
const greet = () => {
  console.log("Hello");
  return "done";
};

// Rest Parameters
const sum = (...nums) => {
  let total = 0;
  for (const n of nums) total += n;
  return total;
};

ตัวอย่างโค้ด

<!DOCTYPE html>
<html lang="th">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Fat Arrow Functions</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result { font-size: 20px; font-weight: 500; color: blueviolet; }
  </style>
</head>
<body>
  <h1>Fat Arrow Functions ใน JavaScript</h1>
  <div class="result"></div>
  <button class="Btn">คลิกที่นี่</button>
  <h3>กดปุ่มเพื่อเรียก Fat Arrow Function add()</h3>
  <script>
    const resEle = document.querySelector(".result");
    const add = (a, b) => {
      return a + b;
    };
    document.querySelector(".Btn").addEventListener("click", () => {
      resEle.textContent = "ผลรวม 32 + 19 = " + add(32, 19);
    });
  </script>
</body>
</html>

ผลลัพธ์

Fat Arrow Functions ใน JavaScript: Block Body และ Explicit Return

เมื่อกดปุ่ม "คลิกที่นี่":

Fat Arrow Functions ใน JavaScript: Block Body และ Explicit Return

เมื่อไหร่ควรใช้ Fat Arrow

  • มีหลาย Statement (Variable declarations, Loops, Conditionals)
  • มี Side Effects (Console.log, DOM manipulation, API calls)
  • ต้องการ try/catch/finally
  • Complex Logic ที่อ่านง่ายกว่าแบบแยกบรรทัด
  • Debugging: Stack trace ชัดเจนกว่า Concise (บาง Engine)

ตัวอย่างใช้งานจริง

// Async Fat Arrow
const fetchUser = async (id) => {
  try {
    const response = await fetch(`/api/users/${id}`);
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return await response.json();
  } catch (error) {
    console.error("Fetch user failed:", error);
    throw error; // Re-throw
  }
};

// Array Processing with Logic
const processItems = (items) => {
  const valid = items.filter(item => item.active);
  const sorted = valid.sort((a, b) => a.priority - b.priority);
  const enriched = sorted.map(item => ({
    ...item,
    processedAt: new Date().toISOString()
  }));
  return enriched;
};

// Event Handler with Logic
const handleSubmit = (event) => {
  event.preventDefault();
  const formData = new FormData(event.target);
  const data = Object.fromEntries(formData);
  if (!validate(data)) return showError("Invalid");
  submitData(data).then(showSuccess).catch(showError);
};

Fat vs Concise: Style Guide แนะนำ

// Airbnb / StandardJS: ใช้ Concise สำหรับ one-liner, Fat สำหรับหลายบรรทัด
// Prettier: จัดรูปแบบอัตโนมัติ

// ✅ Concise - เรียบง่าย
const double = x => x * 2;
const add = (a, b) => a + b;
const getFullName = ({ first, last }) => `${first} ${last}`;

// ✅ Fat - ซับซ้อน
const calculate = (items) => {
  const subtotal = items.reduce((sum, item) => sum + item.price, 0);
  const tax = subtotal * 0.07;
  const discount = subtotal > 1000 ? subtotal * 0.1 : 0;
  return subtotal + tax - discount;
};

⚠️ ข้อผิดพลาดทั่วไป

// ❌ ลืม return
const bad = (a, b) => {
  a + b; // คืน undefined
};

// ✅ มี return
const good = (a, b) => {
  return a + b;
};

// ❌ คืนค่า Object ผิด
const badObj = () => { name: "John" }; // Block, no return

// ✅ ใช้ Concise สำหรับ Object
const goodObj = () => ({ name: "John" });