Arrow function expressions
BaselineWidely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2016.
Anarrow function expression is a compact alternative to a traditionalfunction expression, with some semantic differences and deliberate limitations in usage:
- Arrow functions don't have their ownbindings to
this
,arguments
, orsuper
, and should not be used asmethods. - Arrow functions cannot be used asconstructors. Calling them with
new
throws aTypeError
. They also don't have access to thenew.target
keyword. - Arrow functions cannot use
yield
within their body and cannot be created as generator functions.
Try it
const materials = ["Hydrogen", "Helium", "Lithium", "Beryllium"];console.log(materials.map((material) => material.length));// Expected output: Array [8, 6, 7, 9]
Syntax
() => expressionparam => expression(param) => expression(param1, paramN) => expression() => { statements}param => { statements}(param1, paramN) => { statements}
Rest parameters,default parameters, anddestructuring within params are supported, and always require parentheses:
(a, b, ...r) => expression(a = 400, b = 20, c) => expression([a, b] = [10, 20]) => expression({ a, b } = { a: 10, b: 20 }) => expression
Arrow functions can beasync
by prefixing the expression with theasync
keyword.
async param => expressionasync (param1, param2, ...paramN) => { statements}
Description
Let's decompose a traditional anonymous function down to the simplest arrow function step-by-step. Each step along the way is a valid arrow function.
Note:Traditional function expressions and arrow functions have more differences than their syntax. We will introduce their behavior differences in more detail in the next few subsections.
// Traditional anonymous function(function (a) { return a + 100;});// 1. Remove the word "function" and place arrow between the argument and opening body brace(a) => { return a + 100;};// 2. Remove the body braces and word "return" — the return is implied.(a) => a + 100;// 3. Remove the parameter parenthesesa => a + 100;
In the example above, both the parentheses around the parameter and the braces around the function body may be omitted. However, they can only be omitted in certain cases.
The parentheses can only be omitted if the function has a single simple parameter. If it has multiple parameters, no parameters, or default, destructured, or rest parameters, the parentheses around the parameter list are required.
// Traditional anonymous function(function (a, b) { return a + b + 100;});// Arrow function(a, b) => a + b + 100;const a = 4;const b = 2;// Traditional anonymous function (no parameters)(function () { return a + b + 100;});// Arrow function (no parameters)() => a + b + 100;
The braces can only be omitted if the function directly returns an expression. If the body has statements, the braces are required — and so is thereturn
keyword. Arrow functions cannot guess what or when you want to return.
// Traditional anonymous function(function (a, b) { const chuck = 42; return a + b + chuck;});// Arrow function(a, b) => { const chuck = 42; return a + b + chuck;};
Arrow functions are not inherently associated with a name. If the arrow function needs to call itself, use a named function expression instead. You can also assign the arrow function to a variable, allowing you to refer to it through that variable.
// Traditional Functionfunction bob(a) { return a + 100;}// Arrow Functionconst bob2 = (a) => a + 100;
Function body
Arrow functions can have either anexpression body or the usualblock body.
In an expression body, only a single expression is specified, which becomes the implicit return value. In a block body, you must use an explicitreturn
statement.
const func = (x) => x * x;// expression body syntax, implied "return"const func2 = (x, y) => { return x + y;};// with block body, explicit "return" needed
Returning object literals using the expression body syntax(params) => { object: literal }
does not work as expected.
const func = () => { foo: 1 };// Calling func() returns undefined!const func2 = () => { foo: function () {} };// SyntaxError: function statement requires a nameconst func3 = () => { foo() {} };// SyntaxError: Unexpected token '{'
This is because JavaScript only sees the arrow function as having an expression body if the token following the arrow is not a left brace, so the code inside braces ({}) is parsed as a sequence of statements, wherefoo
is alabel, not a key in an object literal.
To fix this, wrap the object literal in parentheses:
const func = () => ({ foo: 1 });
Cannot be used as methods
Arrow function expressions should only be used for non-method functions because they do not have their ownthis
. Let's see what happens when we try to use them as methods:
"use strict";const obj = { i: 10, b: () => console.log(this.i, this), c() { console.log(this.i, this); },};obj.b(); // logs undefined, Window { /* … */ } (or the global object)obj.c(); // logs 10, Object { /* … */ }
Another example involvingObject.defineProperty()
:
"use strict";const obj = { a: 10,};Object.defineProperty(obj, "b", { get: () => { console.log(this.a, typeof this.a, this); // undefined 'undefined' Window { /* … */ } (or the global object) return this.a + 10; // represents global object 'Window', therefore 'this.a' returns 'undefined' },});
Because aclass's body has athis
context, arrow functions asclass fields close over the class'sthis
context, and thethis
inside the arrow function's body will correctly point to the instance (or the class itself, forstatic fields). However, because it is aclosure, not the function's own binding, the value ofthis
will not change based on the execution context.
class C { a = 1; autoBoundMethod = () => { console.log(this.a); };}const c = new C();c.autoBoundMethod(); // 1const { autoBoundMethod } = c;autoBoundMethod(); // 1// If it were a normal method, it should be undefined in this case
Arrow function properties are often said to be "auto-bound methods", because the equivalent with normal methods is:
class C { a = 1; constructor() { this.method = this.method.bind(this); } method() { console.log(this.a); }}
Note:Class fields are defined on theinstance, not on theprototype, so every instance creation would create a new function reference and allocate a new closure, potentially leading to more memory usage than a normal unbound method.
For similar reasons, thecall()
,apply()
, andbind()
methods are not useful when called on arrow functions, because arrow functions establishthis
based on the scope the arrow function is defined within, and thethis
value does not change based on how the function is invoked.
No binding of arguments
Arrow functions do not have their ownarguments
object. Thus, in this example,arguments
is a reference to the arguments of the enclosing scope:
function foo(n) { const f = () => arguments[0] + n; // foo's implicit arguments binding. arguments[0] is n return f();}foo(3); // 3 + 3 = 6
In most cases, usingrest parametersis a good alternative to using anarguments
object.
function foo(n) { const f = (...args) => args[0] + n; return f(10);}foo(1); // 11
Cannot be used as constructors
Cannot be used as generators
Theyield
keyword cannot be used in an arrow function's body (except when used within generator functions further nested within the arrow function). As a consequence, arrow functions cannot be used as generators.
Line break before arrow
An arrow function cannot contain a line break between its parameters and its arrow.
const func = (a, b, c) => 1;// SyntaxError: Unexpected token '=>'
For the purpose of formatting, you may put the line break after the arrow or use parentheses/braces around the function body, as shown below. You can also put line breaks between parameters.
const func = (a, b, c) => 1;const func2 = (a, b, c) => ( 1);const func3 = (a, b, c) => { return 1;};const func4 = ( a, b, c,) => 1;
Precedence of arrow
Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently withoperator precedence compared to regular functions.
let callback;callback = callback || () => {};// SyntaxError: invalid arrow-function arguments
Because=>
has a lower precedence than most operators, parentheses are necessary to avoidcallback || ()
being parsed as the arguments list of the arrow function.
callback = callback || (() => {});
Examples
Using arrow functions
// An empty arrow function returns undefinedconst empty = () => {};(() => "foobar")();// Returns "foobar"// (this is an Immediately Invoked Function Expression)const simple = (a) => (a > 15 ? 15 : a);simple(16); // 15simple(10); // 10const max = (a, b) => (a > b ? a : b);// Easy array filtering, mapping, etc.const arr = [5, 6, 13, 0, 1, 18, 23];const sum = arr.reduce((a, b) => a + b);// 66const even = arr.filter((v) => v % 2 === 0);// [6, 0, 18]const double = arr.map((v) => v * 2);// [10, 12, 26, 0, 2, 36, 46]// More concise promise chainspromise .then((a) => { // … }) .then((b) => { // … });// Arrow functions without parameterssetTimeout(() => { console.log("I happen sooner"); setTimeout(() => { // deeper code console.log("I happen later"); }, 1);}, 1);
Using call, bind, and apply
Thecall()
,apply()
, andbind()
methods work as expected with traditional functions, because we establish the scope for each of the methods:
const obj = { num: 100,};// Setting "num" on globalThis to show how it is NOT used.globalThis.num = 42;// A traditional function to operate on "this"function add(a, b, c) { return this.num + a + b + c;}console.log(add.call(obj, 1, 2, 3)); // 106console.log(add.apply(obj, [1, 2, 3])); // 106const boundAdd = add.bind(obj);console.log(boundAdd(1, 2, 3)); // 106
With arrow functions, since ouradd
function is essentially created on theglobalThis
(global) scope, it will assumethis
is theglobalThis
.
const obj = { num: 100,};// Setting "num" on globalThis to show how it gets picked up.globalThis.num = 42;// Arrow functionconst add = (a, b, c) => this.num + a + b + c;console.log(add.call(obj, 1, 2, 3)); // 48console.log(add.apply(obj, [1, 2, 3])); // 48const boundAdd = add.bind(obj);console.log(boundAdd(1, 2, 3)); // 48
Perhaps the greatest benefit of using arrow functions is with methods likesetTimeout()
andEventTarget.prototype.addEventListener()
that usually require some kind of closure,call()
,apply()
, orbind()
to ensure that the function is executed in the proper scope.
With traditional function expressions, code like this does not work as expected:
const obj = { count: 10, doSomethingLater() { setTimeout(function () { // the function executes on the window scope this.count++; console.log(this.count); }, 300); },};obj.doSomethingLater(); // logs "NaN", because the property "count" is not in the window scope.
With arrow functions, thethis
scope is more easily preserved:
const obj = { count: 10, doSomethingLater() { // The method syntax binds "this" to the "obj" context. setTimeout(() => { // Since the arrow function doesn't have its own binding and // setTimeout (as a function call) doesn't create a binding // itself, the "obj" context of the outer method is used. this.count++; console.log(this.count); }, 300); },};obj.doSomethingLater(); // logs 11
Specifications
Specification |
---|
ECMAScript® 2026 Language Specification # sec-arrow-function-definitions |
Browser compatibility
See also
- Functions guide
- Functions
function
function
expression- ES6 In Depth: Arrow functions on hacks.mozilla.org (2015)