Arrow function lebih pendek, tetapi perbedaan sebenarnya terletak pada perilaku binding, bukan hanya sintaks.
const regular = function () {};
const arrow = () => {};
const short = x => x * 2; // implicit return for one expression
Arrow function lebih pendek, tetapi perbedaan sebenarnya terletak pada perilaku binding, bukan hanya sintaks.
const regular = function () {};
const arrow = () => {};
const short = x => x * 2; // implicit return for one expression
1. Tidak memiliki this sendiri — arrow mewarisi this dari scope yang mengelilinginya. Ini adalah perbedaan paling penting dan mengapa mereka bagus untuk callback:
const timer = {
seconds: 0,
start() {
setInterval(() => this.seconds++, 1000); // ✅ `this` is timer
// a regular function here would have its own `this` (undefined) → bug
},
};
2. Tidak memiliki objek arguments — gunakan rest parameter sebagai gantinya:
const sum = (...args) => args.reduce((a, b) => a + b, 0);
3. Tidak dapat digunakan sebagai constructor — new arrow() melempar error, dan mereka tidak memiliki prototype.
const obj = {
name: "Ann",
greet: () => `Hi ${this.name}`, // ❌ `this` is NOT obj (it's outer scope)
greet2() { return `Hi ${this.name}`; }, // ✅ method needs dynamic `this`
};
Jangan gunakan arrow untuk object methods (mereka tidak akan bind ke objek) atau ketika Anda memerlukan this/arguments yang dinamis (event handler yang bergantung pada this menjadi element).
Gunakan arrow untuk callback dan fungsi pendek di mana mewarisi this adalah yang Anda inginkan; gunakan regular function untuk method, constructor, dan prototype method.