Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Fat Arrow Function (Arrow Function) trong JavaScript là gì?


Fat arrow function giúp giảm dòng code, cú pháp =>, không cần từ khóa function lặp lại.

Cú pháp

// Một tham số
argument => expression

// Nhiều tham số
(argument1, argument2) => expression

// Khối lệnh (block body) - cần return explicit
(arg1, arg2) => {
  const result = arg1 + arg2;
  return result;
}

// Không tham số
() => expression

So sánh: Function thường vs Arrow Function

Function truyền thống

var rank = [7, 8, 9];
var display = rank.map(function(num) {
  return num * num;
});

Fat Arrow Function

var rank = [7, 8, 9];
var display = rank.map((num) => num * num);
// document.write(display) // sửa: display là array, cần join hoặc log
console.log(display); // [49, 64, 81]

Arrow function chắc chắn giảm dòng code và dễ đọc cho callback đơn giản.

Đặc điểm quan trọng

Đặc điểmArrow FunctionRegular Function
thisLexical (từ scope cha)Dynamic (tùy call site)
argumentsKhông có (dùng rest params ...args)Có
newKhông thể dùng làm constructorCó thể
prototypeKhông cóCó
superLexical (từ class cha)Dynamic
Implicit returnCó (expression body)Không

Khi nào dùng Arrow Function?

  • ✅ Callback: .map(), .filter(), .reduce(), setTimeout, event handler.
  • ✅ Utility functions đơn giản: const add = (a, b) => a + b;
  • ✅ IIFE: (() => { ... })().
  • ❌ Object method (trừ class field).
  • ❌ Constructor/Prototype.
  • ❌ Cần arguments object.
  • ❌ Cần dynamic this (event handler gắn trực tiếp element).

Implicit Return vs Block Body

// Implicit return (expression body) - ngắn gọn
const double = x => x * 2;
const add = (a, b) => a + b;

// Block body - cần return explicit
const sum = (a, b) => {
  const result = a + b;
  return result;
};

// Return object literal - cần wrap bằng ()
const createUser = (name, age) => ({ name, age }); // ✅
// const createUser = (name, age) => { name, age }; // ❌ syntax error