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.
Javascript
function multiply(a, b) {
return a * b;
}
console.log(multiply(3, 5));
|
Below code uses Arrow function to perform the multiplication in single line.
Javascript
value = (a, b) => a * b;
console.log(value(3, 5));
|
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:
Javascript
number = (a, b) => {
c = 5;
return (a + b) * c;
};
console.log(number(2, 3));
|
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:
Javascript
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.
Javascript
let array = ["sam", "sarah", "john"];
let lengths = array.map((string) => string.length);
console.log(lengths);
|
“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
this context. Instead, they inherit the this value from the enclosing scope. This is known as lexical scoping.
- No binding of
this: Unlike regular functions, arrow functions do not bind their own this. In regular functions, this is 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 of this in an arrow function is the same as the value of this in 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
this can 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.
Javascript
function RegularFunction() {
this.value = 42;
setTimeout(function() {
console.log("Regular Function:", this.value);
}, 100);
setTimeout(() => {
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. |
Similar Reads
ES6 Arrow Function
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 JavaScrip
5 min read
ES6 Functions
The ES6 function is the same as a normal function, but ES6 has some differences. A function is a set of instruction that takes some inputs, do some specific task and produce output. A function is a set of codes that can be reused in the program at any time. Syntax: function func-name() { // body } f
6 min read
PHP Arrow Functions
Arrow functions, also known as "short closures", is a new feature introduced in PHP 7.4 that provides a more concise syntax for defining anonymous functions. Arrow functions allow you to define a function in a single line of code, making your code more readable and easier to maintain. Syntax: $fn =
1 min read
Even Function
Even function is defined as a function that follows the relation f(-x) equals f(x), where x is any real number. Even functions have the same range for positive and negative domain variables. Due to this, the graph of even functions is always symmetric about the Y-axis in cartesian coordinates. In th
6 min read
When should one use Arrow functions in ES6 ?
In this article, we will try to understand when should one use Arrow functions in ES6 instead of the traditional function's syntax with the help of some examples. Before analyzing why we should use arrow functions, let us first understand the basic details which are associated with the arrow functio
4 min read
Arrow functions in JavaScript
An arrow function is a shorter syntax for writing functions in JavaScript. Introduced in ES6, arrow functions allow for a more concise and readable code, especially in cases of small functions. Unlike regular functions, arrow functions don't have their own this, but instead, inherit it from the surr
5 min read
ES6 Trampoline Function
In this article, we will try to understand each and every aspect associated with Trampoline function in ES6 in as much detailed manner as possible. Let us first understand what actually went wrong while working with Recursion, followed by understanding the Tail Recursion concept and thereafter we wi
4 min read
How to define a function in ES6 ?
In this article, we will try to understand basic details which are associated with the function definition, like syntax declaration of a function or some examples associated with different types of functions declarations in ES6 (EcmaScript-6). Let us first understand what exactly the function is and
3 min read
ES6 | Array forEach() Method
When working with arrays, it's widespread to iterate through its elements and manipulate them. Traditionally this can be done using for, while or do-while loops. The forEach will call the function for each element in the array. Syntax: array.forEach( callback, thisObject ) Parameter: This method acc
3 min read
Named Function Expression
In JavaScript or in any programming language, functions, loops, mathematical operators, and variables are the most widely used tools. This article is about how we can use and what are the real conditions when the Named function Expressions. We will discuss all the required concepts in this article t
3 min read