Functions in JavaScript are one of the most important parts of your code. You use a function when you want to perform a task or calculate something. Over the course of time, JavaScript has evolved a lot, and one of the most important updates was the arrow functions in JavaScript introduced in ES6 (ECMAScript 2015). While learning JavaScript, it is important for you to understand what arrow functions are, how they work, and when you should use them.
In this blog, we are going to talk about everything about arrow functions in JavaScript. So let’s get started!
Table of Contents:
What is an Arrow Function in JavaScript?
An arrow function in JavaScript is a shorter and more modern way to write a function. Instead of using the function keyword, you can use a special symbol =>, which helps to define a function. This makes your code look simple and easier to read, especially when the function is small. Arrow functions are mostly used in situations where you need quick and one-line logic, like inside methods such as map(), filter(), or forEach(0), which work with arrays.
Get Job-Ready Web Development Skills
Kickstart Your Tech Career
Syntax of the arrow function
const functionName = (parameter1, parameter2, ...) => {
// body of the function
// statements or logic
};
Explanation: The above syntax is used to define an arrow function that is assigned to a constant variable. It takes the parameters and executes the code inside the body of the function.
Example of Arrow Function in JavaScript
Given below is a simple code to help you understand the concept:
Output:
Explanation:
In the above code, at first, the traditional function is defined, which is named greetTraditional. It takes a name as input and then returns a greeting message by adding “Hello” before the name. Next, the arrow function is defined called greetArrow, which does the same thing but in a shorter way using the => syntax. Finally, the traditional function is called with the name “Intellipaat” and the result is printed using the console.log(), which displays “Hello Intellipaat” as the output. Both the traditional function and the arrow function do the same thing, but the arrow function is shorter.
Types of Arrow Functions in JavaScript
You can write an arrow function in JavaScript in different ways depending on the number of parameters it takes and what it returns. It is important for you to understand these types, as it will help you to write cleaner and efficient code. Given below are the different types of arrow functions in JavaScript:
1. Arrow Function without Parameters
An arrow function without parameters means that the function does not need any input values. In this case, you have to use empty parentheses () before the arrow. This can be helpful when you want the function to perform actions without any arguments.
Code:
Output:
Explanation:
The above JavaScript code is used to define an arrow function named sayHello. It uses no parameters; therefore, it uses empty parentheses (). Inside the function, it returns the string “Hello!”. When the function sayHello() is called using console.log, it returns the function and prints the returned message to the console.
2. Arrow Function with a Single Parameter
If the arrow function takes only one parameter, you don’t have to put that value inside the parentheses. You can just write the name of the parameter directly before the arrow. This helps to make the code shorter and easier to read.
Code:
Output:
Explanation:
In the above code, an arrow function is created named greet, which takes one input called name. Since there is only one parameter, you don’t have to use parentheses around it. Inside the function, “Hello” is combined with the value that is passed, and returns the full message. When the function greet(“Intellipaat”) is called, it returns with “Hello, Intellipaat”, and it is printed on the screen using console.log.
Get 100% Hike!
Master Most in Demand Skills Now!
3. Arrow Function with Multiple Parameters
When the arrow function needs more than one parameter, you have to write them in parentheses like this: (param1, param2) => { }. This helps you to write functions that work with more than one value, like adding two numbers or comparing two items. This helps to make your code shorter and easier to read while you are still handling more than one argument.
Code:
Output:
Explanation:
In the above JavaScript code, the arrow function is named as add, which takes two inputs, a and b. These values are written inside the parentheses because there is more than one parameter. Inside the function, the two numbers are added together using a + b, and then the result is returned. When you call add(5, 3), it adds the numbers 5 and 3. After that, console.log prints the result.
4. Arrow Function with Default Parameters
Arrow functions may also take default values for their parameters. This means that if you don’t pass a value while calling the function, it will use a default value. This makes your function flexible as it can still operate even if you don’t provide it with all the inputs.
Code:
Output:
Explanation:
In the above JavaScript code, an arrow function is used. It is named as greetUser, which contains a default parameter. The name of the parameter is set to “Guest” by default. This means if you call the function without giving any name to it, it will use the name “Guest” by default.
- In greetUser(), no name is given to the function, so it returns the value “Welcome to, Guest”.
- In greetUser(“Intellipaat”), the name Intellipaat is given to the function; therefore, it returns “Welcome to, Intellipaat”.
5. Arrow functions: Returning Objects
In JavaScript, if you want an arrow function to return an object directly, you need to write the object in parentheses like this: () => ({ key: value }). This informs JavaScript that you are just returning an object and not opening a new block of code. It is a simple way to create and return an object in one line.
Code:
Output:
Explanation:
In the above code, an arrow function is used, which is named as getUser, and it returns an object directly. Since an object is returned in one line, you can write it in parentheses () so that JavaScript doesn’t get confused and think it is a code block.
The object consists of two properties:
- name which has the value “XYZ”.
- age, which has the value 25.
When the function getUser() is called, it returns XYZ and 25, and the result is printed using console.log.
Async Arrow Functions
Arrow functions in JavaScript can also be used to handle asynchronous tasks by using the async keyword. This helps you to write non-blocking code for fetching data or reading files. The code execution can be paused until the promise has resolved by taking the following actions: before the arrow function, you can write async, and inside the function, add await. This causes your asynchronous code to look cleaner and more functional, particularly when you are operating with APIs or dynamic information.
The JavaScript code for the async arrow function is given below:
Code:
Explanation:
The above code is used to define an async arrow function named fetchData. It is used to fetch data from the API link https://jsonplaceholder.typicode.com/users/1. It waits for the output using await and converts the response into JSON. After that, the data is displayed inside an HTML element with the ID output.
Given below is the entire HTML code so that you can get the desired output:
Output:
Arrow Function vs Regular Function
The difference between an Arrow function and a Regular function is given below in tabular format:
Feature |
Arrow Function |
Regular Function |
Syntax |
Written in a shorter way using => |
Written using the function keyword |
this keyword |
Uses this from where the function was written |
It has its own this keyword based on how the function is called |
Constructor Support |
It can’t be used to create objects with the new keyword. |
It can be used to create objects using the new keyword. |
arguments object |
Doesn’t have its own arguments object. |
It has access to the arguments object by default. |
Advantages of Arrow Functions
The advantages of arrow functions in JavaScript are given below:
1. Shorter Syntax: With the help of arrow functions, you can write less code to do the same thing. This makes it faster to write and easier to read.
2. No binding of this keyword: Arrow functions use the value of this keyword from the place where they are written so that you don’t have to worry about this changing inside callbacks or event handlers.
3. Cleaner code in callbacks: The arrow functions are the most ideal to write a short line of code within a method such as map(), filter(), or forEach().
4. More readable for small tasks: If you use the arrow function correctly, small operations become easier for you to understand.
5. Avoids the unwanted behavior of this keyword: Arrow functions can be useful in classes and objects because they help to keep the value of this the same as the outer code.
Disadvantages of Arrow Functions
The disadvantages of arrow functions in JavaScript are given below:
1. Can’t be used as constructors: With arrow functions, you cannot use the new keyword to create objects in the same manner as normal functions.
2. No Own this keyword context: In some situations, like inside objects or classes, arrow functions without their own this keyword can create confusion.
3. No arguments object: Arrow functions do not receive the built-in argument object that is used during regular functions.
4. Not ideal for all use cases: Arrow functions are not ideal to be used for complex logics, longer functions, or class methods.
5. May reduce the clarity of code when overused: When you use arrow functions everywhere, including situations where normal functions can be used, it can make your code harder to understand.
Best Practices for Arrow Functions
Some of the best practices for Arrow functions are given below:
1. You should always use arrow functions for short and simple tasks. This makes your code clean and readable.
2. You should not use arrow functions as object methods if you use this keyword.
3. You should not use arrow functions as constructors. This is because they cannot be called with the new keyword.
4. You should use parentheses for multiple parameters. This will make your code easy to read.
5. You should always write object returns in parentheses so that JavaScript knows that you are returning an object, and not a block of code.
Conclusion
In conclusion, arrow function in JavaScript makes your code shorter, cleaner, and easier to read when you are writing basic tasks or working with functions like map() or filter(). They help avoid confusion with the this keyword by using the value from the surrounding code. Although arrow functions have some limitations, like not being usable as constructors, they are still a great tool in modern JavaScript development. By learning how to use them the right way, you make your JavaScript code more powerful and efficient. You need to keep practicing and use these functions in your projects so that you can write better and shorter code in JavaScript. To learn more about JavaScript, explore the JavaScript Interview Questions and subscribe to our Web Development Course.
Arrow Function in JavaScript - FAQs
Q1. Can I use arrow functions with setTimeout or setInterval?
Yes, arrow functions are used with setTimeout and setInterval, particularly when you want to maintain the this keyword value from the outer scope.
Q2. Can I use arrow functions inside a class constructor?
Arrow functions can only be used for defining methods inside a class constructor. It cannot be used as the constructor itself, because arrow functions cannot be used with the new keyword.
Q3. Do arrow functions support rest parameters ( …args )?
Yes, it is possible to have rest parameters fully supported by arrow functions in order to support a changing number of arguments.
Q4. Can arrow functions be recursive?
Yes, but you must assign the arrow function to a named constant or variable to call itself.
Q5. Are arrow functions supported in all browsers?
Arrow functions are supported in all modern browsers, but not in Internet Explorer.