What is the difference between an arrow function and a regular function?
Quick Answer
Arrow functions have no this of their own — they inherit it from the enclosing scope (lexical this). They also have no arguments object, can't be used as constructors (new), and have no prototype. Regular functions get this from how they're called.
The big one is this: an arrow function doesn't have its own this, it uses whatever this is in the surrounding code, which is exactly what you want in a callback. A regular function's this depends entirely on how it's called. Arrows also don't have the arguments object — you use rest parameters — and you can't new them. So I use arrows for callbacks and array methods, and regular functions for object methods where this should be the object, and for constructors.
- Use an arrow for callbacks and array methods where you want
thisto stay as the outerthis(React class methods, event handlers that access component state). - Use a regular function for object methods that need
thisto be the object, for constructors, and for generators. - Arrows can't be generators; use the rest parameter
(...args)instead ofarguments.