Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Operators

Arrow function expressions (=>)

Reference for JavaScript arrow functions: concise syntax, implicit returns, lexical this, no arguments or constructor, and when not to use them.

An arrow function is a compact way to write a function expression using =>. Besides the shorter syntax it behaves differently from a regular function in a few important ways: it has no this, arguments, super or new.target of its own (it uses those of the surrounding code), and it cannot be used as a constructor.

Arrow functions shine as short callbacks for map(), filter(), sort() and promise chains, and wherever you want a function to keep the this of the place where it was written.

JavaScript
(a, b) => a + b

Try it

JS Syntax variations

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Lexical this

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
() => expression
param => expression
(param1, param2, ...rest) => expression
(param1 = 1, { a, b }) => { statements }
async (x) => expression
Part Description
Parameters Same options as a normal function: defaults, destructuring and rest. A single plain identifier may omit the parentheses; zero parameters need ().
=> Must be on the same line as the closing parenthesis of the parameters.
Expression body The expression is evaluated and returned automatically.
Block body { ... } Ordinary statements; use return to produce a value, otherwise the result is undefined.

Return value: the expression result (concise body) or whatever return provides (block body). The arrow function expression itself evaluates to a function object.

Exceptions: calling an arrow function with new throws a TypeError. Syntax errors occur if there is a line break before => or if you write duplicate parameter names.

Usage notes

  • Lexical this. this inside an arrow function is whatever it was where the arrow was created. call(), apply() and bind() cannot change it.
  • No arguments. Use rest parameters instead, or the arguments of an enclosing regular function is seen.
  • Not constructors, with no prototype property and no new.target.
  • Not generators. There is no arrow generator syntax; yield is not available. async arrows are fine, though.
  • Returning an object literal requires parentheses: () => ({ ok: true }).
  • Avoid as object methods or prototype methods when you need this to be the object: { count: 0, inc: () => this.count++ } does not use the object.
  • Name inference. const f = () => {} gives the function the name "f", which helps stack traces. Anonymous arrows passed inline show up unnamed.
  • Readability. Long arrow bodies with nested ternaries are hard to follow; use a named function.
  • Class fields. Arrow functions in class fields capture the instance, a common way to keep event handler this.

Browser support

Supported in every current browser (ES2015).