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
// Normal function for multiplication
// of two numbers
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
// Arrow function for multiplying two numbers
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
// Arrow function with no parameters
const string = () => "geeksforgeeks";
console.log(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
// 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]
"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;
// 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();
OutputRegular 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
PHP Arrow Functions
PHP arrow functions are a shorthand syntax for anonymous functions. It was introduced in PHP 7.4, which provides a shorter way to write anonymous functions. They allow you to create functions with fewer lines of code while maintaining functionality. They provide an easy-to-read syntax, particularly
5 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 an
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
Node forEach() function
forEach() is an array function Node that is used to iterate over items in a given array. Syntax: array_name.forEach(function)Parameter: This function takes a function (which is to be executed) as a parameter. Return type: The function returns an array element after iteration. The program below demon
1 min read
Introduction to ES6
ES6 or ECMAScript 2015 is the 6th version of the ECMAScript programming language. ECMAScript is the standardization of Javascript which was released in 2015 and subsequently renamed as ECMAScript 2015.New Features in ES61. The let KeywordThe let variables are mutable i.e. their values can be changed
4 min read
Slope of a Function
The slope of a function is a fundamental concept in mathematics that describes how the output of a function changes in response to changes in its input. In simple terms, the slope tells us how steep a curve or line is and whether it is increasing or decreasing.While the concept of slope is commonly
9 min read
Arrow operator in ES6 of JavaScript
ES6 has come with various advantages and one of them is the arrow operator. It has reduced the function defining code size so it is one of the trending questions asked in the interview. Let us have a deeper dive into the arrow operator's functioning. Syntax: In ES5 a function is defined by the foll
4 min read