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

Concise Arrow Functions ใน JavaScript: Implicit Return


Concise Arrow Function (Concise Body) เป็นรูปแบบย่อของ Arrow Function ที่มีเพียง Expression เดียว — ไม่ต้องเขียน {} และ return ค่าจะถูกคืนอัตโนมัติ (Implicit Return)

Syntax

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

// พารามิเตอร์เดียว (ไม่ต้องวงเล็บ)
const square = x => x * x;

// ไม่มีพารามิเตอร์ (ต้องมีวงเล็บ)
const random = () => Math.random();

// คืนค่าอ็อบเจกต์ (ต้องห่อด้วยวงเล็บ)
const createUser = (name, age) => ({ name, age });

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

<!DOCTYPE html>
<html lang="th">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Concise 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>Concise Arrow Functions ใน JavaScript</h1>
  <div class="result"></div>
  <button class="Btn">คลิกที่นี่</button>
  <h3>กดปุ่มเพื่อเรียก Concise Arrow Function add()</h3>
  <script>
    const resEle = document.querySelector(".result");
    const add = (a, b) => a + b;
    document.querySelector(".Btn").addEventListener("click", () => {
      resEle.textContent = "ผลรวม 32 + 19 = " + add(32, 19);
    });
  </script>
</body>
</html>

ผลลัพธ์

Concise Arrow Functions ใน JavaScript: Implicit Return

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

Concise Arrow Functions ใน JavaScript: Implicit Return

กรณีใช้งานที่เหมาะสม

  • Array Methods: arr.map(x => x * 2), arr.filter(x => x > 0), arr.reduce((a,b) => a+b, 0)
  • Promise Chains: fetch(url).then(r => r.json()).then(data => ...)
  • Event Handlers สั้น: btn.addEventListener("click", () => doSomething())
  • Utility Functions: const clamp = (v, min, max) => Math.max(min, Math.min(max, v));
  • React/JSX: const Component = () => <div>Hello</div>;

ข้อจำกัด

  • ไม่สามารถใช้ break, continue, return (ในความหมายของการออกจากฟังก์ชัน) ได้ภายใน — เพราะไม่มี block
  • ไม่สามารถประกาศตัวแปรด้วย const/let/var ได้ภายใน
  • Debugging: Stack trace อาจแสดงเป็น anonymous (ใช้ named arrow: const add = (a,b) => a+b; ช่วยบ้าง)

Common Pitfalls

// ❌ คืนค่า Object ผิด
const bad = () => { foo: "bar" }; // Block ไม่มี return → undefined

// ✅ ถูก
const good = () => ({ foo: "bar" });

// ❌ ใช้ statement แทน expression
const bad2 = (x) => if (x > 0) x; // SyntaxError

// ✅ ใช้ ternary
const good2 = (x) => (x > 0 ? x : 0);

// ❌ forEach ไม่รองรับ break/continue
[1,2,3].forEach(x => { if (x===2) return; }); // return ออกจาก callback ไม่ใช่ loop

// ✅ ใช้ for...of
for (const x of [1,2,3]) { if (x===2) break; }

Performance

ไม่มีความแตกต่างด้านประสิทธิภาพระหว่าง Fat และ Concise — Engine จัดการเหมือนกัน เลือกตาม Readability และ Team Style Guide