Fat arrow: có block {} và return rõ ràng. Concise arrow: một biểu thức, implicit return (không cần return, không cần {}). Nếu 1 tham số -> bỏ (). 0 tham số -> cần ().
Cú pháp
// Fat arrow
const add = (a, b) => { return a + b; };
// Concise arrow
const add = (a, b) => a + b;
// 1 tham số
const double = a => a * 2;
Ví dụ
So sánh 2 kiểu:
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Fat vs Concise Arrow</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 vs Concise Arrow Function</h1>
<div class="result"></div>
<button class="Btn">THỰC HIỆN</button>
<h3>Nhấn để gọi cả 2 kiểu arrow function</h3>
<script>
const resEle = document.querySelector(".result");
const add = (a, b) => a + b; // concise
const multiply = (a, b) => { return a * b; }; // fat
document.querySelector(".Btn").addEventListener("click", () => {
resEle.innerHTML = `Concise add(32,19) = ${add(32, 19)}<br>`;
resEle.innerHTML += `Fat multiply(32,19) = ${multiply(32, 19)}`;
});
</script>
</body>
</html>
Kết quả
Cả hai cho kết quả: add = 51, multiply = 608.
Khi nào dùng cái nào? Concise cho one-liner đơn giản. Fat cho logic phức tạp, nhiều dòng, hoặc cần return sớm.