Le arrow functions sono più corte, ma le vere differenze sono nel comportamento del binding, non solo nella sintassi.
const regular = function () {};
const arrow = () => {};
const short = x => x * 2; // implicit return for one expression
Le arrow functions sono più corte, ma le vere differenze sono nel comportamento del binding, non solo nella sintassi.
const regular = function () {};
const arrow = () => {};
const short = x => x * 2; // implicit return for one expression
1. No own this — le arrow ereditano this dal scope che le racchiude. Questa è la differenza più importante e per questo sono ottime per i 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. No arguments object — usa invece i rest parameters:
const sum = (...args) => args.reduce((a, b) => a + b, 0);
3. Cannot be used as constructors — new arrow() genera un errore, e non hanno 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`
};
Non usare le arrow per metodi di oggetti (non si legheranno all'oggetto) o quando hai bisogno di un this dinamico/arguments (event handler che si affidano a this come elemento).
Usa le arrow per i callback e le funzioni brevi dove ereditare this è quello che vuoi; usa le regular functions per i metodi, i costruttori e i metodi di prototype.
Una raccolta di domande di colloquio IT con risposte dettagliate — da Junior a Senior.
Dona