Arrow function

On this page 7

An arrow function is a concise function expression introduced in ECMAScript 2015 (ES6) that is written with the => token and does not create its own `this` binding. In browser JavaScript, arrow functions are the default choice for callbacks, array transformations and promise chains, because they keep the surrounding context without the manual binding that older code required.

The syntax is shorter than a classic function expression, but the important difference is semantic. An arrow function captures `this`, `arguments`, `super` and `new.target` lexically, cannot be used as a constructor and has no prototype property. These rules make arrow functions predictable inside event handlers, timers and class fields, yet they also make them the wrong tool for object methods that rely on a dynamic receiver.

How arrow function syntax works

An arrow function consists of a parameter list, the => token and a body, which is either a single expression or a block in braces. With a concise body, the value of the expression is returned automatically; with a block body, the function returns undefined unless it contains an explicit return statement.

The following table shows the main syntactic forms and what each one returns.

FormExampleReturn behavior
No parameters() => 42Returns 42 implicitly
Single parameterx => x * 2Parentheses optional, implicit return
Several parameters(a, b) => a + bParentheses required
Block body(a) => { return a; }Explicit return needed
Object literal result() => ({ id: 1 })Parentheses around the object required
Async arrowasync () => await load()Always returns a Promise
Arrow function syntax forms

Two parsing details cause frequent bugs. An object literal in a concise body must be wrapped in parentheses, because otherwise the braces are read as a block and the function returns undefined. In addition, a line break is not allowed between the parameter list and the => token, which matters when code formatters or manual edits split long lines.

Lexical this and the other inherited bindings

An arrow function resolves `this` from the enclosing scope at the moment it is created, exactly like any other free variable. A regular function, by contrast, receives this from how it is called: as a method, through call or apply, as a constructor or as a plain call in which this is undefined in strict mode.

Because the binding is fixed, `call`, `apply` and `bind` cannot change `this` for an arrow function; they only pass the arguments. The table compares the behavior that matters in day-to-day browser code.

FeatureArrow functionRegular function
thisInherited from the defining scopeSet by the call site
arguments objectNot available, use rest parametersAvailable
Use with newThrows a TypeErrorAllowed for constructors
prototype propertyAbsentPresent
Duplicate parameter namesAlways a syntax errorAllowed in sloppy mode
HoistingFollows its variable declarationDeclarations are fully hoisted
Generator formNot possiblePossible with function*
Arrow functions compared with regular functions

The hoisting row deserves attention. An arrow function is always an expression assigned to a variable, so a const arrow is in the temporal dead zone until its line runs, while a function declaration can be called before it appears in the source. Code that relies on calling helpers near the top of a file therefore behaves differently after a mechanical conversion.

Where arrow functions fit in browser code

Arrow functions are best suited to short callbacks that should share the outer context. Typical cases are array methods such as map, filter and reduce, the then and catch handlers of a Promise, setTimeout callbacks inside class methods and the inline handlers of the Fetch API.

A common pattern is the arrow function as a class field, for example handleClick = (event) => { this.count++; }. Each instance receives its own function whose this always points to that instance, so the method can be passed to addEventListener without bind. The trade-off is memory per instance: the function is not shared on the prototype, which is noticeable only when thousands of instances exist.

The decision table below summarizes when to choose each form.

SituationRecommended formReason
Array transformationArrow functionShort and context-free
Callback inside a class methodArrow functionKeeps the instance as this
Object literal method using thisMethod shorthandNeeds the calling object
Event listener needing currentTarget via thisRegular functionThe DOM sets this to the element
Constructor or factory with newClass or regular functionArrows cannot be constructed
Recursive or reusable helperFunction declarationHoisted and named in stack traces
Choosing between arrow and regular functions

Common mistakes with arrow functions

Most problems arise when developers treat arrow functions as shorter syntax only and ignore the binding rules. The mistakes below appear regularly in code review.

SymptomCauseFix
this is undefined inside an object methodMethod defined as an arrowUse method shorthand
Function returns undefined instead of an objectBraces parsed as a blockWrap the object in parentheses
this is not the clicked element in a listenerArrow ignores the DOM receiverUse event.currentTarget
ReferenceError for argumentsArrows have no arguments objectUse rest parameters
Listener cannot be removedNew inline arrow on each callStore the reference in a variable
Typical errors, causes and fixes

The last row is especially relevant for event listener cleanup. removeEventListener requires the same function reference that was registered, so an inline arrow passed to addEventListener can never be detached. Keeping the arrow in a variable or a class field solves the leak. Anonymous arrows also appear without a useful name in older stack traces, although modern engines infer the name from the variable that holds the function.

Performance and compatibility

In current engines, arrow functions have no meaningful performance penalty compared with regular functions; the choice should be made on semantics and readability. All evergreen browsers support them, and only Internet Explorer 11 lacks support, which is why legacy builds still transpile arrows with Babel into regular functions that capture this in a variable such as _this.

  • Readability suffers when deeply nested arrows hide the flow; named functions are clearer for complex logic.
  • Implicit returns shorten code but can hide accidental results, so block bodies are safer for side effects.
  • Lint rules such as prefer-arrow-callback encourage arrows for callbacks while leaving methods as regular functions.

Put simply

An arrow function is a shorter way to write a small piece of reusable code in JavaScript. Its special feature is that it remembers where it was written. A regular function asks who is calling it each time, while an arrow function simply uses the context around it.

Think of a note that says “give this to the manager”. A regular function reads the note and gives it to whoever manages the room it is in now. An arrow function always gives it to the manager of the office where the note was first written. That is convenient for small helper tasks, but unsuitable when the code must adapt to the object using it.

In practice

A frontend developer builds a product gallery with a Gallery class that loads images through the Fetch API and updates a counter after each successful request. The first version used a regular function inside then, and the counter update failed with this is undefined, because the callback lost the class instance.

Replacing the callback with response => this.addImage(response) fixed the error at once, since the arrow inherited this from the surrounding method. The developer also stored the scroll handler as a class field arrow, onScroll = () => this.loadMore(), so it could be registered with addEventListener and later removed with the same reference when the gallery closed. The result was a component with no manual bind calls and no listener leaks, while the object literal configuration kept method shorthand for functions that needed their own receiver.