1. What Is an Anonymous Function
An anonymous function is a function that does not have an explicit function name.
Compared with ordinary named functions, anonymous functions are usually not called directly by name; instead, they are used through variables, parameters, return values, or other expressions.
1.1 Named Functions
function add(a, b) {
return a + b;
}
const result = add(10, 20);
A named function has an explicit identifier add and can be called by name.
1.2 Anonymous Functions
const add = function (a, b) {
return a + b;
};
const result = add(10, 20);
Here, function (a, b) has no explicit name, so it is an anonymous function.
The function is assigned to the variable add and can later be called through the variable.
Note: the variable name add does not automatically become the function's explicit internal name. The function expression itself can still be anonymous, although the JavaScript engine may infer a function name in some cases for debugging and error stacks.
1.3 Main Characteristics of Anonymous Functions
- No explicitly declared function name.
- It can be assigned to a variable.
- It can be passed as a function argument.
- It can be returned as a function's return value.
- It can be defined directly in an expression where a function value is needed.
- It can capture the outer lexical environment and form a closure.
An anonymous function is not a separate execution mechanism; it is a form of function definition.
2. What Is a Lambda Expression
A Lambda expression is an expression form that uses concise syntax to define a function or callable behavior.
Different languages do not define Lambda in exactly the same way:
- In languages such as Java and C++, Lambdas are usually used to create anonymous function objects.
- In Python,
lambdais the syntax used to define single-expression anonymous functions. - In JavaScript, arrow functions are a common Lambda-style expression form.
- In C#, Lambdas can represent expression-bodied or statement-bodied functions.
For example, in JavaScript:
const add = (a, b) => a + b;
console.log(add(10, 20)); // 30
Where:
(a, b): parameter list.=>: arrow symbol.a + b: expression body.add: the variable that stores the function value.
The main goal of Lambda is to reduce the syntax required to define a function, so that functions can be embedded in expressions more naturally.
3. Relationship Between Anonymous Functions and Lambdas
Anonymous functions and Lambdas are often discussed together, but they are not exactly the same concept.
| Comparison Dimension | Anonymous Function | Lambda Expression |
|---|---|---|
| Core meaning | A function without an explicit name | A function-definition syntax |
| Focus | Whether it has a name | How a function is expressed |
| Syntax form | Depends on the language | Depends on the language |
| Whether it must be anonymous | Yes, by the usual definition | Not necessarily; depends on the language |
| Whether it can be assigned | Yes | Usually yes, subject to the language's type system |
| Whether it can be used as a parameter | Yes | Usually yes |
The two overlap, but one cannot simply assume that every anonymous function is a Lambda, nor that every Lambda must be anonymous.
For example, in JavaScript:
// Anonymous function expression
const fn1 = function (x) {
return x * 2;
};
// Arrow function, the common Lambda-style syntax
const fn2 = x => x * 2;
Both can be used as function values, but their syntax forms are different.
4. Function Expression Forms in Different Languages
4.1 JavaScript: Function Expressions and Arrow Functions
JavaScript has two common forms of anonymous function expressions.
Regular function expression:
const multiply = function (a, b) {
return a * b;
};
Arrow function:
const multiply = (a, b) => a * b;
Arrow functions have more concise syntax, but they are not a completely equivalent replacement for regular function expressions.
Main differences:
| Feature | Normal Function | Arrow Function |
|---|---|---|
this |
Dynamically determined by how it is called | Inherits the outer lexical this |
arguments |
Usually has its own arguments |
Does not have its own arguments |
new call |
Normal functions can be used as constructors (with limitations) | Cannot be used as constructors |
prototype |
Normal functions usually have a prototype property |
Do not have their own prototype property |
super |
Restricted by function type and definition location | Uses super from the outer lexical environment |
yield |
Normal functions cannot use it directly; generator functions can | Cannot be used directly as generator functions |
Pay special attention to the difference in this:
const user = {
name: "Reverie",
normal: function () {
return this.name;
},
arrow: () => {
return this.name;
}
};
console.log(user.normal()); // Reverie
console.log(user.arrow()); // usually not Reverie
A normal function's this is determined by how it is called, whereas an arrow function's this comes from the lexical environment where it is defined.
Therefore, arrow functions are usually suitable for callbacks and short data-processing logic, but they should not unconditionally replace object methods.
4.2 Python: Lambda Expressions
Python uses the lambda keyword to define anonymous functions.
add = lambda a, b: a + b
print(add(10, 20)) # 30
Its basic syntax:
lambda 参数列表: 表达式
Python Lambda has an important limitation:
The body of a Lambda can only be a single expression and cannot directly contain multiple ordinary statements.
For example:
# Valid
square = lambda x: x * x
# Not suitable for implementing complex multi-statement logic with lambda
Complex logic should usually use def:
def calculate(a, b):
result = a + b
return result * 2
Python Lambda is commonly used in:
users = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 20},
{"name": "Tom", "age": 25}
]
users.sort(key=lambda user: user["age"])
Here, the Lambda provides a sorting key function for sort.
4.3 Java: Lambda and Functional Interfaces
Java has officially supported Lambda expressions since Java 8.
Java does not directly pass arbitrary functions as independent values; instead, it carries Lambdas through functional interfaces (Functional Interface).
A functional interface is an interface with exactly one abstract method; default methods and static methods do not affect this condition.
@FunctionalInterface
interface Calculator {
int calculate(int a, int b);
}
public class Main {
public static void main(String[] args) {
Calculator add = (a, b) -> a + b;
System.out.println(add.calculate(10, 20));
}
}
Java also provides common built-in functional interfaces:
| Interface | Main purpose | Abstract method |
|---|---|---|
Function<T, R> |
Takes an input and returns a result | apply |
Consumer<T> |
Accepts an argument, returns no value | accept |
Supplier<T> |
Takes no arguments, provides a result | get |
Predicate<T> |
Conditional test | test |
BiFunction<T, U, R> |
Takes two arguments and returns a result | apply |
Example:
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
Function<Integer, Integer> square =
x -> x * x;
System.out.println(square.apply(5)); // 25
}
}
4.4 C++: Lambda Expressions
Lambda expressions have been supported since C++11.
Basic syntax:
[capture](parameters) -> return_type {
// function body
};
Where:
capture: captures external variables.parameters: the parameter list.return_type: the return type, which can be deduced by the compiler.- Function body: the actual logic to execute.
Example:
#include <iostream>
int main() {
int factor = 10;
auto multiply = [factor](int value) {
return value * factor;
};
std::cout << multiply(5) << std::endl;
return 0;
}
Output:
50
An important feature of C++ lambdas is that the capture list controls how external variables are accessed.
Common capture forms:
| Form | Meaning |
|---|---|
[] |
Captures no external variables |
[x] |
Captures x by value |
[&x] |
Captures x by reference |
[=] |
Captures the external local variables that are used, by value by default |
[&] |
Captures the external local variables that are used, by reference by default |
[this] |
Captures the this pointer of the current object |
[*this] |
Captures a copy of the current object by value (since C++17) |
A C++ lambda essentially forms a closure object, and its concrete type is generated by the compiler.
4.5 Go: Anonymous Functions and Closures
Go supports anonymous functions, which can be defined and called directly, or assigned to a variable.
package main
import "fmt"
func main() {
add := func(a, b int) int {
return a + b
}
fmt.Println(add(10, 20))
}
Go's anonymous functions can also capture external variables:
package main
import "fmt"
func main() {
count := 0
increment := func() int {
count++
return count
}
fmt.Println(increment()) // 1
fmt.Println(increment()) // 2
}
Go has no separate lambda keyword, but anonymous functions and closures can achieve similar functionality.
4.6 Rust: Closure Expressions
Rust uses closure expressions to define anonymous function behavior.
fn main() {
let add = |a: i32, b: i32| -> i32 {
a + b
};
println!("{}", add(10, 20));
}
Rust closures can capture the external environment:
fn main() {
let factor = 10;
let multiply = |value| value * factor;
println!("{}", multiply(5));
}
Closure capture in Rust is closely tied to the ownership system, and call behavior is mainly described by the following traits:
Fn: captures the environment through an immutable borrow.FnMut: captures the environment through a mutable borrow.FnOnce: allows the captured environment to be consumed.
Note that a closure does not necessarily implement all three traits. Which ones it implements depends on how the closure uses the captured variables.
V. Lambda and Closures
Lambda and closures often appear together, but they sit at different conceptual levels.
- Lambda: describes how a function is defined.
- Closure: describes how a function establishes a connection with the external lexical environment.
A lambda may capture no external variables at all, or it may capture external variables to form a closure.
5.1 Not Capturing External Variables
const square = x => x * x;
This arrow function does not depend on any external variables.
5.2 Capturing External Variables
function createMultiplier(factor) {
return value => value * factor;
}
const double = createMultiplier(2);
console.log(double(10)); // 20
Here the arrow function references the external variable factor.
Even after createMultiplier finishes executing, the returned function can still access factor.
5.3 How a Closure Forms
flowchart TD
A["Define the outer function"] --> B["Create the outer lexical environment"]
B --> C["Define the inner lambda"]
C --> D["Reference an external variable"]
D --> E["Form a closure relationship"]
E --> F["Return the inner function"]
F --> G["Outer function finishes executing"]
G --> H["Later call to the inner function"]
H --> I["Access the captured variable"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style I fill:#FFF5DE,stroke:#E8D29A,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
5.4 Capture Mechanisms in Different Languages
| Language | Capture mechanism | Key characteristics |
|---|---|---|
| JavaScript | Lexical scope | Accesses external variables at the definition site |
| Python | Closure cells and lexical scope | Outer bindings can be modified with nonlocal |
| Java | Captures local variables | Local variables must be final or effectively final |
| C++ | Explicit capture list | Value capture and reference capture can be controlled |
| Go | Lexical closures | Can reference external variables |
| Rust | Ownership and borrowing | Capture mode is constrained by the closure traits |
C++ and Rust deserve particular attention:
- In C++, when capturing by reference, if the closure outlives the referenced object, a dangling reference may result.
- Rust uses borrow checking and lifetime constraints to restrict unsafe reference escapes.
VI. Lambda Types and Execution Mechanisms
Lambda is not just a syntactic shorthand. Different languages turn lambdas into different function values, objects, or intermediate representations.
6.1 Function Types
A lambda usually needs explicit input and output types.
For example:
means that the function f takes an input of type A and returns a result of type B.
A multi-parameter function can be represented as:
For example:
const add = (a, b) => a + b;
This can be understood as a function that takes two inputs and returns one result.
Type systems in different languages may express this relationship using function types, functional interfaces, closure types, or template types.