ES6 Arrow functions enable us to write functions with simpler and shorter syntax and make our code more readable and organised. The arrow functions are introduced in the ES6 version. Arrow functions provides us with a more precise approach to writing JavaScript Functions.
Arrow Function in JavaScript
Arrow functions are anonymous functions i.e. they are functions without a name and are not bound by an identifier. Arrow functions do not return any value and can be declared without the function keyword. They are also called Lambda Functions.
- Arrow functions do not have the prototype property like this, arguments, or super.
- Arrow functions cannot be used with the new keyword.
- Arrow functions cannot be used as constructors.
Syntax:
For Single Argument:
let function_name = argument1 => expression
For Multiple Arguments:
let function_name = (argument1, argument2 , ...) => expression
Note: In case of multiple arguments you need to enclose the arguments within brackets.
Example 1:
This code uses the traditional way of defining functions.
// Normal function for multiplication
// of two numbers
function multiply(a, b) {
return a * b;
}
console.log(multiply(3, 5));
Output
15
Below code uses Arrow function to perform the multiplication in single line.
// Arrow function for multiplying two numbers
value = (a, b) => a * b;
console.log(value(3, 5));
Output
15
Example 2: Arrow functions with multiple lines
From the previous example, we can see that when there's a single line of code to be executed we didn't use the return keyword but if there are more than two lines to be processed, we need to use a return keyword. let's demonstrate that with an example:
number = (a, b) => {
c = 5;
return (a + b) * c;
};
console.log(number(2, 3));
Output
25
Example 3: Arrow function with no parameters. In the below code, we use an arrow function without any parameters and return the word "geeksforgeeks" as it is a single statement we don't need to use the return keyword.
Syntax:
()=>{ expressions}Example:
// Arrow function with no parameters
const string = () => "geeksforgeeks";
console.log(string);
Output
[Function: string]
Example 4: Using the arrow function inside another function. In this example let's find the length of strings in an array. we use the arrow function inside the map() function to accomplish this task. arrow function returns the length of each string.
// Initializing an array of strings
let array = ["sam", "sarah", "john"];
// Map function used to find the length of strings
let lengths = array.map((string) => string.length);
console.log(lengths); // [3,5,4]
Output
[ 3, 5, 4 ]
"this" in arrow function:
The this keyword behaves differently in arrow functions compared to regular functions.
- Lexical scoping: Arrow functions do not have their own
thiscontext. Instead, they inherit thethisvalue from the enclosing scope. This is known as lexical scoping. - No binding of
this: Unlike regular functions, arrow functions do not bind their ownthis. In regular functions,thisis determined by how the function is called, leading to potential issues in certain situations. Arrow functions eliminate this ambiguity. - Use of surrounding
this: The value ofthisin an arrow function is the same as the value ofthisin the surrounding (enclosing) scope. This can be beneficial when working with callback functions or methods within objects. - Commonly used in callbacks: Arrow functions are often preferred in callback functions where the lexical scoping of
thiscan be advantageous, avoiding the need for workarounds like using.bind()or creating a closure.
Example: Here, the arrow function inside setTimeout correctly captures the this value from the surrounding RegularFunction, while the regular function inside setTimeout has its own this context, causing potential issues.
function RegularFunction() {
this.value = 42;
// Regular function with its own 'this' context
setTimeout(function() {
// 'this' here refers to the global object (or undefined in strict mode)
console.log("Regular Function:", this.value);
}, 100);
// Arrow function inheriting 'this' from the enclosing scope
setTimeout(() => {
// 'this' here refers to the 'this' of the enclosing RegularFunction
console.log("Arrow Function:", this.value);
}, 200);
}
const instance = new RegularFunction();
Output
Regular Function: undefined Arrow Function: 42
Differences between Traditional and Arrow Functions:
| Feature | Traditional Function | Arrow Function |
|---|---|---|
| Usage as a Method | Suitable, has its own this binding. | Not suitable, lacks its own this binding. |
Use of yield within its body | Can use yield in a generator function. | Unable to use yield within its body. |
| Presence of Return Statements | Can be used with return statements. | Should not be used if return statements exist. |
Keyword Targeted (let, var, const) | No specific restriction on variable keywords. | No specific restriction on variable keywords. |
Methods (call, apply, bind) | Suited for methods, allows setting a scope. | Not suitable for methods that require scope setting (call, apply, bind). |
Object Creation (new keyword) | Can be used as a constructor function. | Cannot be used with the new keyword to create a new object. |
Presence of arguments object | Has arguments object available. | Lacks the arguments object. |
Presence of prototype property | Has a prototype property. | Lacks the prototype property. |