EMZETT.
Login

Lambda (Lambda Expression)

In short: A compact, nameless function defined directly where it’s needed — a shorter alternative to a full named method or anonymous class for short, one-off logic.

In more detail: Lambda expressions are often passed as an argument to other functions, e.g. to specify how a collection should be filtered, transformed, or sorted — instead of a dedicated named comparison method, a short expression right on the spot is enough. The concept comes from functional programming, but has since become established in almost all modern languages.

In Depth

The name “lambda” comes from lambda calculus, a mathematical formalism for functions from the 1930s — in practice today, simply a compact shorthand for “a function I don’t want to name separately and define somewhere else”.

// classic, named function
function isEven(number) {
    return number % 2 === 0;
}
 
// the same as a lambda/arrow function, right on the spot
numbers.filter(number => number % 2 === 0)

Lambda expressions are especially often used together with higher-order functions — functions that themselves accept another function as an argument (e.g. filter, map, sort/sortBy). Instead of defining a separate, one-off, named function somewhere in the code for every individual use case, the logic is written directly at the spot where it’s needed — this keeps related code together and reduces “naming clutter” for functions that otherwise wouldn’t be reused anywhere.

An important concept that often shows up together with lambdas is the closure: a lambda expression can access variables from its surrounding environment, even though it itself is only executed later (e.g. asynchronously or in another function):

function createMultiplier(factor) {
    return number => number * factor;   // "remembers" factor even after being returned
}
double = createMultiplier(2)
double(5)   // gives 10

A common style mistake is using lambda expressions for logic that’s too complex or multi-line — they’re meant for short, self-explanatory expressions; once the logic gets longer or has to be reused multiple times, a named method is almost always the more readable choice.

See also: Anonymous Classes, Methods, Sorting