![]() |
VOOZH | about |
A lambda expression also known as arrow-function is a function without a name defined using the arrow => syntax introduced in ES6 (ECMAScript 2015). Unlike traditional function declarations or expressions, lambda expressions are shorter and come with some unique behavior, particularly around the this keyword.
Now let's understand with the help of an example
45
Syntax
const functionName = (parameters) => { // function body };Below are the some examples of arrow functions:
This is a typical arrow function that performs an operation (adding two numbers)
8
If the function contains only one expression, you can omit the curly braces and return statement. The result will be returned automatically
20
If the function has no parameters, simply use empty parentheses:
Hello, World!
If there is only one parameter, you can omit the parentheses:
36
Arrow functions are commonly used with array methods like map(), which require a callback function.
Output
[2, 4, 6, 8, 10]Arrow functions are often used in event listeners because they automatically bind this to the surrounding context.
Arrow functions are often used for small, inline functions, where defining a function with a function keyword might seem excessive.
.map(), .filter(), .reduce().this: Especially in event handlers, timers, or nested functions.Here are some limitations:
Traditional Functions | Lambda Functions |
|---|---|
Uses the function keyword. | Uses the => (fat arrow) syntax for a more concise function |
The value of this is dynamically bound based on how the function is invoked. | this is lexically bound and takes the value from the surrounding context. |
Has its own arguments object which contains all arguments passed to the function. | Does not have its own arguments object, instead inherits it from the surrounding function. |
Can be used as a constructor with the new keyword to create instances. | Cannot be used as a constructor, will throw an error when used with new. |
Functions have the prototype property and can be used to create methods on objects. | Arrow functions do not have a prototype property. |
Suitable for functions where you need to work with this, constructors, or the arguments object. | Ideal for short functions, callbacks, and cases where this needs to be inherited from the surrounding context. |
Example => function add(a, b) { return a + b; } | Example => const add = (a, b) => a + b; |