JavaScript lambda functions and expressions: arrow functions explained

A lambda function, or lambda expression, in JavaScript is an anonymous function written as an expression, and in modern JavaScript that means an arrow function: (a, b) => a + b. Arrow functions arrived in ES2015 (ES6). They are shorter than function expressions, and they take this and arguments from the code around them instead of having their own. That makes them a good fit for callbacks and a poor fit for object methods and constructors.
Lambda expressions are present in most modern programming languages (JavaScript, Python, Ruby, Java, etc.). They are expressions mainly used to create concise (usually single-line) anonymous functions, making them a powerful feature of the JavaScript language and an essential concept for modern web development. I’ll explore their syntax and showcase practical examples to illustrate how they can be used to write more concise and expressive code.
For more on how we work with JavaScript, see our JavaScript engineering insights.
Key takeaways
What it is
A JavaScript lambda is an arrow function: an anonymous function written as an expression, such as (x) => x * 2.
Where it fits
Callbacks for map, filter, reduce, setTimeout and promises, where a short function that keeps the outer this helps.
Where it doesn't
Object methods and constructors. An arrow function has no this, arguments or prototype of its own and can’t be called with new.
What to watch
Wrap a returned object literal in parentheses, () => ({ id: 1 }), and don’t pass an async arrow to forEach when you need to wait for it.
What is a lambda function in JavaScript?
Lambda expressions in JavaScript are often referred to as arrow functions. They allow the creation of function expressions without needing the traditional function keyword.
“Lambda” is the general name for a function you write inline, without a name, and pass around as a value. JavaScript has had those since its first version, because functions are values: function (x) { return x * 2; } can be stored in a variable or handed to another function. When people say “lambda” in JavaScript today, though, they nearly always mean the arrow syntax, =>, which the language specification calls an arrow function. So arrow functions are JavaScript’s lambdas, and what sets them apart from a function expression is how they behave, covered in arrow function vs. regular function below.
Other languages draw the line differently. Python’s lambda, for instance, can hold only a single expression (more on lambdas in Python), while a JavaScript arrow function can have a full block body.
Arrow function syntax
Let’s take a closer look at the syntax of arrow functions. In JavaScript, you can make a one line Javascript anonymous lambda function with arrow functions:
const anon = (a, b) => a + b;An arrow function is concise and convenient, providing a shorter syntax for anonymous functions. Here’s another example of similar functionality, but now with multiple lines:
const anon = (a, b) => {
return a + b;
};When you have a single parameter, you can even omit the parentheses:
const anon = a => a * 50;And if you have no parameters, it would look like this:
const anon = () => {};Every form at a glance:
const greet = () => 'hello'; // no parameters
const double = (x) => x * 2; // one parameter (parentheses optional)
const add = (a, b) => a + b; // several parameters
const hello = (name = 'world') => `hello, ${name}`; // default value
const count = (...items) => items.length; // rest parameters
const sum = (a, b) => {
const total = a + b;
return total; // a block body needs an explicit return
};
const toRecord = (id) => ({ id }); // an object literal goes in parentheses
const getJson = async (url) => (await fetch(url)).json(); // async arrowArrow function vs. regular function
Both are functions you can store and pass around. They differ in what they bring with them:
| Arrow function | Regular function | |
|---|---|---|
this |
Taken from the surrounding code | Set by how the function is called |
arguments |
None of its own | Its own arguments object |
new |
Throws TypeError: ... is not a constructor |
Can be used as a constructor |
prototype property |
None | Has one |
call, apply, bind |
Pass arguments, but can’t change this |
Can set this |
Generators (yield) |
Not allowed | function* |
| Hoisting | Always an expression, so it exists only after its line runs | A function declaration is hoisted; an expression is not |
In practice, the first row is the one that matters most: use an arrow function when you want the this of the code around it, and a regular function or method when the function needs its own.
Should you use an arrow function or a function declaration?
Both work; what matters is that a codebase picks one rule and keeps it. A common split:
- Function declarations for named, top-level functions. They are hoisted, so a module can call a helper defined further down the file, and
export default function OrderList()reads as what it is. - Arrow functions for everything passed as a value: callbacks, handlers, short helpers and functions returned from other functions.
Stack traces are not a reason to avoid arrows. Since ES2015, const add = (a, b) => a + b gets add as its name, so the function shows up by name in errors and profilers. ESLint can hold part of the rule for you: func-style with allowArrowFunctions keeps function expressions out of variables, and prefer-arrow-callback keeps function callbacks out. Where top-level functions go stays a team convention:
// eslint.config.js
export default [
{
rules: {
'func-style': ['error', 'declaration', { allowArrowFunctions: true }],
'prefer-arrow-callback': 'error',
},
},
];Advantages of JavaScript arrow functions
Depending on the context, the simplified syntax of arrow functions can make your code more readable and elegant. For instance, you can transform this:
// Returns Array [ 2, 4 ]
[1, 2, 3, 4].filter(function (value) {
return value % 2 === 0;
});Into this:
[1, 2, 3, 4].filter(value => value % 2 === 0);Using arrow functions can reduce code verbosity and improve readability by eliminating the need for the function keyword and providing a shorter syntax for declaring functions.
The other significant advantage of arrow functions is that they do not have their own this. Inside an arrow function, this is lexically bound to the enclosing scope. Arrow functions eliminate the need for workarounds like saving the this value in a separate variable to access it inside a callback function, resulting in cleaner and more intuitive code. See the example below, which dumps data to a file and gets the name of the file through a callback. Before arrow functions, the usual workaround was to save this in a variable:
class Logger {
dumpData(data) {
var _this = this;
dump(data, function (outputFile) {
_this.latestLog = outputFile;
});
}
}With arrow functions, we just use this directly:
class Logger {
dumpData(data) {
dump(data, (outputFile) => (this.latestLog = outputFile));
}
}Although, in that case, the lexical binding of this is helpful, arrow functions lead to some gotchas, covered in when not to use arrow functions.
Arrow functions as class fields
Modern classes go one step further. Since ES2022, a class can declare fields, and a field holding an arrow function keeps this bound to the instance wherever the function is passed. That is the usual way to write a handler you hand to someone else:
class Uploader {
progress = 0;
// A class field: `this` is always this Uploader, even when the function is passed around
handleProgress = (event) => {
this.progress = event.loaded / event.total;
};
start(file) {
upload(file, { onProgress: this.handleProgress });
}
}The cost is that the function lives on each instance, not on the class’s prototype. Every instance gets its own copy, a subclass can’t call it through super.handleProgress(), and a test can’t replace it on the prototype. Keep regular methods for everything that isn’t passed around, and use arrow fields only for the handlers that are.
How to use arrow functions as callbacks: map, filter, reduce and forEach
Callbacks are where arrow functions are used the most. Array methods take a function and call it once per item:
const orders = [
{ id: 1, total: 40, paid: true },
{ id: 2, total: 25, paid: false },
{ id: 3, total: 60, paid: true },
];
const paidTotals = orders.filter((order) => order.paid).map((order) => order.total); // [40, 60]
const revenue = paidTotals.reduce((sum, total) => sum + total, 0); // 100
const byTotal = orders.toSorted((a, b) => a.total - b.total); // a sorted copy; orders is unchanged
const byStatus = Object.groupBy(orders, (order) => (order.paid ? 'paid' : 'open'));
// { paid: [order 1, order 3], open: [order 2] }
orders.forEach((order) => console.log(order.id));toSorted (ES2023) and Object.groupBy (ES2024) work in every current browser and replace the old [...orders].sort() copy and the hand-written reduce for grouping. forEach returns undefined, so use map when you need a new array and forEach only for side effects such as logging. The same short form works for timers and promise chains:
setTimeout(() => console.log('one second later'), 1000);
fetch('/api/orders')
.then((response) => response.json())
.then((orders) => console.log(orders.length));How to write an async arrow function
Put async before the parameters. The function then returns a promise, and you can use await inside it:
const getUser = async (id) => {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
return response.json();
};The common mistake is passing an async arrow to forEach. forEach does not wait for promises, so the loop finishes before any request does. Use Promise.all with map to run the calls in parallel, or a for...of loop to run them one at a time:
// Doesn't wait: forEach ignores the promises the callback returns
ids.forEach(async (id) => {
await getUser(id);
});
// In parallel, waiting for all of them
const users = await Promise.all(ids.map((id) => getUser(id)));
// One at a time, in order
const inOrder = [];
for (const id of ids) {
inOrder.push(await getUser(id));
}These examples use await outside a function, which works only at the top level of an ES module (a .mjs file, type: "module" in package.json, or <script type="module">). Anywhere else, put them inside an async function.
Promise.all rejects as soon as one call fails. When you want every result, failed or not, use Promise.allSettled:
const results = await Promise.allSettled(ids.map((id) => getUser(id)));
const users = results.filter((r) => r.status === 'fulfilled').map((r) => r.value);
const failures = results.filter((r) => r.status === 'rejected').map((r) => r.reason);Arrow functions in TypeScript
TypeScript types an arrow function’s parameters and return value inline, and can name a function’s shape with a type alias:
const add = (a: number, b: number): number => a + b;
type Comparator<T> = (a: T, b: T) => number;
const byTotal: Comparator<{ total: number }> = (a, b) => a.total - b.total;
const firstItem = <T>(items: T[]): T | undefined => items[0];In a .tsx file, <T> at the start of an arrow function is read as a JSX tag, and the compiler fails with “JSX element ‘T’ has no corresponding closing tag”. Add a trailing comma to make it a type parameter:
const firstItem = <T,>(items: T[]): T | undefined => items[0];In callbacks you rarely write the types yourself. In orders.filter((order) => order.paid), TypeScript already knows order’s type from the array, which keeps typed code as short as plain JavaScript. The satisfies operator (TypeScript 4.9) brings the same to an object of arrow functions: each parameter is typed from the shape you name, and the object keeps its own keys:
type Handler = (event: { type: string }) => void;
const handlers = {
click: (event) => console.log(event.type), // event is typed from Handler
submit: (event) => console.log(event.type),
} satisfies Record<string, Handler>;
handlers.click; // known key; with `: Record<string, Handler>` any string would be allowedFor a wider view of the move to types, see our TypeScript engineering insights.
Arrow functions in React
Most JavaScript developers write their arrow functions in React components: event handlers, the callbacks of map that render lists, and the functions passed to hooks.
function OrderList({ orders, onSelect }) {
const [query, setQuery] = useState('');
const visible = orders.filter((order) => String(order.id).includes(query));
return (
<>
<input value={query} onChange={(event) => setQuery(event.target.value)} />
<ul>
{visible.map((order) => (
<li key={order.id} onClick={() => onSelect(order.id)}>
Order {order.id}
</li>
))}
</ul>
</>
);
}Each render creates those arrow functions again, which used to push teams to wrap them in useCallback so that memoized children would not re-render. React Compiler, stable since version 1.0 in October 2025, memoizes values and functions on its own. React’s documentation recommends relying on it for new code and keeping useCallback and useMemo as an escape hatch, for example for a function used as an effect dependency. In existing code, leave the memoization in place or test carefully before removing it. For more on hooks, see how to adopt React Hooks and our React engineering insights.
When not to use arrow functions
While arrow functions offer remarkable benefits, they also come with a few considerations:
1. Arrow functions do not allow the manipulation of the this value.
Unlike traditional functions, you cannot change the this value using methods like call(), apply() or bind(). Remembering this when working with arrow functions is essential to maintain the proper context.
2. Unlike traditional functions, arrow functions do not have access to the arguments variable:
(function () {console.log(arguments)})(1, 2); // will output [1, 2]
(() => console.log(arguments))(1, 2); // in a browser script or ES module, will raise ReferenceError: arguments is not definedIn a Node.js CommonJS module there is no error: the arrow function reads the arguments of the function Node wraps each module in, which is just as wrong.
The lack of arguments encourages the use of rest parameters or the spread operator to manage function arguments:
((...args) => console.log(args))(1, 2); // will output [1, 2]Read more about rest parameters here.
3. Be careful when returning object literals
// 'foo: 1' is interpreted as a statement composed of a label and the literal 1.
// returns undefined
(() => {foo: 1})();
// the correct way should be wrapping it with parenthesis.
// returns Object {foo: 1}
(() => ({foo: 1}))();4. Don’t use an arrow function as an object method
A method needs this to be the object it is called on, and an arrow function keeps the this of the code around it instead:
const counter = {
count: 0,
increment: () => {
this.count += 1; // `this` is the outer scope's, not `counter`
},
};
const fixedCounter = {
count: 0,
increment() {
this.count += 1; // `this` is `fixedCounter`
},
};5. Arrow functions can’t be constructors
const Person = (name) => {
this.name = name;
};
new Person('Ada'); // TypeError: Person is not a constructorUse a class or a regular function when you need new.
If you’re interested in further improving the reliability and maintainability of your JavaScript projects, take a look at this informative blog post on adding types with TypeScript.
Frequently asked questions
Is an arrow function the same as a lambda function?
In JavaScript, yes. “Lambda” is the general name for an anonymous function passed around as a value, and the arrow function is JavaScript’s syntax for it. A function expression passed as a callback is a lambda too, but it has its own this and arguments, while an arrow function takes them from the code around it.
Is a JavaScript lambda the same as AWS Lambda?
No. AWS Lambda is Amazon’s service for running code without managing servers. The two meet only in syntax: a Node.js function on AWS Lambda is often written as an async arrow function, export const handler = async (event) => { ... };.
Can an arrow function be async?
Yes. Write async before the parameters, const load = async (id) => { ... }, and use await inside. The function returns a promise. Don’t pass an async arrow to forEach when you need to wait for it; use Promise.all with map or a for...of loop.
Can you use this inside an arrow function?
Yes, but it is the this of the code where the arrow function is written, not of the object that calls it. That is what you want in a callback inside a class method, and what breaks an object method written as an arrow function.
Do I still need useCallback for arrow functions in React?
Less than before. With React Compiler (stable since October 2025), React memoizes functions and values for you, and its documentation recommends relying on the compiler in new code. Keep useCallback where you need precise control, such as a function used as an effect dependency, and test before removing it from existing code.
Should I use an arrow function or a function declaration?
Use function declarations for named, top-level functions, since they are hoisted, and arrow functions for callbacks and anything passed as a value. Arrow functions assigned to a variable still get a name, so they show up by name in stack traces. ESLint’s func-style and prefer-arrow-callback rules keep function expressions and function callbacks out; where top-level functions go stays a team convention.
How do you return an object from an arrow function?
Wrap the object literal in parentheses: const toRecord = (id) => ({ id });. Without them, JavaScript reads the braces as a function body and the function returns undefined.
What does the λ symbol mean in the Next.js build output?
It marks a route that is rendered on the server when it is requested, not prerendered at build time, and it has nothing to do with arrow functions. Next.js printed λ up to version 14.1 (labelled (Server) in version 13, (Dynamic) in 14). From 14.2 the same routes are marked ƒ (Dynamic). For what that means for a Next.js app in production, see our Next.js engineering insights.
References
- MDN Web Docs, Arrow function expressions. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
- MDN Web Docs, The arguments object. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
- MDN Web Docs, Rest parameters. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters
- MDN Web Docs, Array.prototype.forEach(). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
- MDN Web Docs, Promise.all(). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
- MDN Web Docs, Promise.allSettled(). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled
- MDN Web Docs, await: top level await. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
- MDN Web Docs, Array.prototype.toSorted(). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSorted
- MDN Web Docs, Object.groupBy(). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/groupBy
- MDN Web Docs, Public class fields. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields
- MDN Web Docs, Function: name. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
- ESLint, func-style and prefer-arrow-callback. https://eslint.org/docs/latest/rules/func-style, https://eslint.org/docs/latest/rules/prefer-arrow-callback
- TypeScript Handbook, More on functions. https://www.typescriptlang.org/docs/handbook/2/functions.html
- TypeScript 4.9 release notes, The satisfies operator. https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html
- React, React Compiler v1.0 (October 7, 2025). https://react.dev/blog/2025/10/07/react-compiler-1
- React documentation, Introduction to React Compiler. https://react.dev/learn/react-compiler/introduction
- Node.js documentation, The module wrapper. https://nodejs.org/api/modules.html#the-module-wrapper
- AWS Lambda Developer Guide, Define Lambda function handler in Node.js. https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html
- Next.js documentation, Building your application. https://nextjs.org/docs/app/guides/building
- Next.js source, build output legend in version 14.1.0. https://github.com/vercel/next.js/blob/v14.1.0/packages/next/src/build/utils.ts
Related articles

Article · 3 min read
Functional programming in Python: the simplest way
The core ideas of functional programming, compared side by side with imperative code.
3 min read

Article · 3 min read
Functional programming in Python: a bit more
Function composition explained, plus practical uses of Python's operator and functools.
3 min read




