Reading — step 1 of 7
Learn
Arrow functions (=>) are a shorter syntax for function expressions. They're especially common as callbacks to array methods (map, filter, reduce), event handlers, and Promise chains.
All the forms
That last one is a famous trap: (a, b) => { a, b } is a function body with two statements, NOT an object. Wrap object literals in ( ... ).
Where arrows shine
Array methods love arrows because the syntax is concise:
Arrows DON'T have their own this
The key behavioral difference from regular functions: arrows inherit this from the enclosing scope. This is usually what you want:
With a regular function callback, this inside the timer callback is set by the timer itself — the global object in browsers, a Timeout object in Node — not your Counter. Either way it is almost certainly not what you want.
When NOT to use arrows
- As object methods that need
this: arrows don't bindthis, soobj.methodwon't getobjasthis. Use a regular function or method shorthand:{ method() { ... } }. - As constructors: arrows can't be called with
new. - When you need
arguments(the magic local variable in regular functions). Use rest params instead:(...args) =>.
Summary table
| Feature | function | arrow |
|---|---|---|
| this binding | own (dynamic) | inherited (lexical) |
| Hoisted (declaration form) | yes | no |
Can be new'd | yes | no |
arguments object | yes | no — use rest params |
| Implicit return | no | yes (single expression) |
Common mistakes
- Returning an object literal without parens:
x => { a: 1 }is a labeled-statement function body, NOT an object. Usex => ({ a: 1 }). - Using arrow for an object method when
thismatters: pick a regular method. - Stripping parens from a 0-arg arrow:
=>x + 1is a syntax error. Always() =>.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…