Voici la traduction de l'article en français, en respectant toutes les règles :
What is it and why? (a real-life analogy)
Imagine you come to an auto repair shop. The mechanic has a huge toolbox: wrenches, screwdrivers, hammers. Each tool is a function. You ask the mechanic: "Tighten the wheel." The mechanic takes a wrench and does the job.
Now imagine you tell the mechanic: "Here's an instruction on how to make a new tool right now, and use it immediately." You don't take a ready-made tool from the box — you describe the action on the spot and perform it right away. This is exactly what a lambda function is (or an arrow function, as it's called in JavaScript).
In programming, it often happens that we need a function "once and for all." For example, to sort an array by some clever rule. Instead of creating a separate named function, giving it a name, writing it somewhere else, we can write it right where it's needed. It's like writing a note "turn right" instead of drawing an entire map.
Important: Lambda functions are not magic, but simply a way to write functions shorter and more conveniently. They make code more "functional," meaning code where functions can be passed to other functions as regular values (numbers, strings).
Why is this needed? Imagine you're writing code to process a shopping list. You need to find all products more expensive than 100 rubles. Instead of writing an entire loop with a condition, you can say: "Take the list and filter it by the rule: price greater than 100." This rule is the lambda function. The code becomes shorter, clearer, and there's less chance of making a mistake.
The functional style is an approach where we combine functions like construction set parts. We don't write long instructions "do step 1, then step 2, then step 3." Instead, we say: "Take the data, apply function A to it, pass the result to function B, and then to function C." This is similar to a factory conveyor belt: raw materials go in, finished product comes out.
Theory: how it works internally
Let's look "under the hood" of JavaScript and understand how lambda functions work.
In JavaScript, functions are first-class objects. What does this mean? It means you can do everything with a function that you can do with a number or string:
- Assign it to a variable
- Pass it to another function as an argument
- Return it from another function as a result
- Put it in an array or object
A lambda function (arrow function) is simply a shorter syntax for creating such a function. But there is one important difference from a regular function: it doesn't have its own this.
Key point:thisinside an arrow function is taken from the outer environment (from the function within which it was created). A regular function creates its ownthis. This is done specifically to avoid confusion in event handlers and callbacks.
How does JavaScript execute a lambda function? When the engine (e.g., V8 in Node.js) encounters an arrow function, it:
- Creates a function object (just like for a regular function).
- Remembers the lexical environment (all variables that are available at the place where the function is created).
- Does not create its own
thiscontext (unlike a regular function). - If the function body consists of a single expression — it returns its result automatically, without the
returnkeyword.
Here's what it looks like in memory (simplified):
// Regular function
function sum(a, b) {
return a + b;
}
// Lambda function (arrow)
const sum = (a, b) => a + b;
// Difference: in lambda there is no function keyword, no return (it is implied),
// and curly braces are not needed if the body is a single expression.
When you write const sum = (a, b) => a + b, JavaScript does the following:
- Creates a variable
sumin the current scope. - Creates an anonymous (unnamed) function with parameters
aandb. - The function body is the expression
a + b. The result of this expression is automatically returned. - Assigns this function to the variable
sum.
Now sum is a function, and it can be called: sum(2, 3) will return 5.
Syntax in JavaScript (Node.js): all forms and variants
Arrow functions have several forms of notation. Let's go through them all.
1. Basic form: one parameter, one expression
// If there is one parameter — parentheses can be omitted
const double = x => x * 2;
console.log(double(5)); // 10
2. Multiple parameters
// If there are several parameters — parentheses are mandatory
const multiply = (a, b) => a * b;
console.log(multiply(3, 4)); // 12
3. No parameters
// If there are no parameters — empty parentheses are needed
const sayHello = () => 'Hello!';
console.log(sayHello()); // Hello!
4. Body with multiple statements
// If you need to perform several actions — use curly braces
// and explicitly write return
const processNumber = (x) => {
const doubled = x * 2;
const message = `Result: ${doubled}`;
return message;
};
console.log(processNumber(7)); // Result: 14
5. Returning an object
// To return an object, you need to wrap it in parentheses
const createUser = (name, age) => ({ name: name, age: age });
console.log(createUser('Anna', 25)); // { name: 'Anna', age: 25 }
// Without parentheses, Ja