Arrow Function in JavaScript – Explained in Detail

Updated on September 13, 2024

Article Outline

JavaScript is a versatile and widely used programming language in the 21st century. Over the years, it has undergone many significant enhancements. One of the most notable additions in ECMAScript 6 (ES6) is the arrow function. In this article, we will explore the arrow function in ES6 in depth.

What is the Arrow Function in JavaScript?

The arrow function, added in ES6, is a concise and powerful alternative to regular functions in JavaScript. The arrow function, also known as the fat arrow function, Arrow function provides a shorthand syntax for writing function expressions. This function is very useful for writing shorter function expressions. 

 

Syntax

// Arrow function let arrowName = (arg1, arg2, ...argN) => { statement(s) }

Breakdown the ArrowFunctionSyntax

  • arrowName: This is the arrow function name.
  • arg1, arg2, …argN: Arguments of the arrow function
  • statements(s): Body of the function

 

Example

 

Let’s add two numbers in javascript.

 

1. Using the Regular JavaScript function

let  addition  = function(num1,num2){ return num1+num2; }

2. Using the Arrow function

let addition = (num1, num2) =>{ return  num1 + num2 ; }
*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Arrow Function in JavaScript without Parameters

We can also use the arrow function without any parameters. To denote the absence of parameters, you must use empty parentheses ().

 

Syntax

() => { /* statements body */ }

Program

const logMessage = () => console.log("Hello Neeraj"); logMessage();

Output

Hello Neeraj

Arrow function with Parameters

The arrow function can take as many parameters as they want as a regular function.

 

Syntax

 

  • Single parameter: param => {statements}
  • Multiple parameters: (param1, param2,..) => {statements}

 

Examples:
Single Parameter

const double = n => n * 4343; console.log(double(5));

Output

21715

Multiple Parameters

const add = (a, b) => a + b; console.log(add(343,343));

Output

686

Arrow Function in JavaScript with Default Parameters

The JavaScript arrow function also supports default parameters. JavaScript developers must initialise the default parameter when they define it in parenthesis.

 

Syntax of Arrow Function

const functionName = (param1 = defaultValue1, param2 = defaultValue2) => { // Function body };

The following program demonstrates the default parameters:

 

Program

const name = (name = 'Neeraj Kumar') => `Hello, ${name}!`; console.log(name('Alice')); console.log(name());     <strong> </strong>

Output

Hello, Alice! Hello, Neeraj Kumar!

Using async with Arrow Function

 

JavaScript developers can also use the async keyword with the arrow function. This helps the developer make the function asynchronous.

 

The following program demonstrates the async with Arrow function:

 

Program

const fetchData = async (url = 'https://api.example.com') => { const response = await fetch(url); const data = await response.json(); return data; };   fetchData().then(data => console.log(data));

Note: Replace the URL parameter with your API link.

Advantages of JavaScript Arrow Function

  • Concise Syntax: The arrow function provides a shorter and more readable way to write a function expression in a JavaScript Program. This reduced boilerplate makes the code cleaner and easier to understand, which is especially beneficial in large codebases.
  • Implicit Return: An arrow function with a single expression allows you to omit the ‘return’ keyword and the curly braces in JavaScript, leading to a more compact syntax.
  • No Duplicates Parameters Name: The arrow function follows strict rules regarding parameter names and does not allow duplicate parameter names. This prevents bugs and enhances code clarity by enforcing a consistent, error-free parameter.

Disadvantages of JavaScript Arrow Function

JavaScript arrow function offers several benefits, but they also come with certain disadvantages. Let’s discuss all those disadvantages.

 

  • Cannot be used as Constructors: The arrow function cannot be used with the ‘new’ keyword. It means we cannot use the Arrow function as a constructor in JavaScript. This limitation of the arrow function makes them unsuitable for creating instances of objects.
  • Hard to debug: The arrow function has concise syntax, but it can sometimes be harder to debug the arrow function in the large code base.
  • Not Suitable for All Callbacks: While the arrow function is great for callbacks, there are cases where a traditional function might be more appropriate, especially when a developer callback needs its own ‘this’ context to access the arguments object.

Also read: JavaScript Interview Questions

Difference between Regular Function and Arrow Function

The following table differentiates the Regular function and Arrow function.

 

Features Regular Function Arrow Function
Syntax function name () {}  ()=> {}
Constructor It can be used as a constructor It cannot be used as a constructor
Self Referencing It can be self-referencing for recursion It cannot be a function declaration only expression.
Versatility It is more versatile in various contexts It is a less versatile function in certain contexts
Prototype It has a ‘prototype’ property The arrow function does not have a prototype property

this keyword with Arrow Function

Let’s discuss the behaviour of the Arrow function with this keyword.

 

  • The arrow function does not have its own context. Instead, it captures the value of the enclosing scope at the time it is created.
  • The arrow function cannot be used as a constructor. If you attempt to use a new keyword with an arrow function. It will throw an error.
  • The arrow function uses the lexical binding. That arrow function is a common choice for writing concise functional expressions.

Conclusion

In this article, we learned about the Arrow function in JavaScript. It provides a modern, concise way to write functions, with several advantages, such as shorter syntax. Arrow functions have a concise syntax, make handling ‘this’ easier by inheriting it from their surrounding scope, and are greatest for callbacks and functional programming. They cannot be used as constructors, and they are not suitable for all scenarios. By understanding the Arrow function, JavaScript developers can enhance the code readability and versatility in JavaScript programming.

FAQs
An arrow function is a concise way to write function expressions in JavaScript in a shorter way.   For example:   const add = (a, b) => a + b;
Writing an arrow function is very easy. Let’s see the example:   Example:   const add = (a, b) => a + b;
No, the Arrow function cannot be used as a constructor or called as the new keyword.
JavaScript developers can use short, non-method functions, especially for callbacks or functions that do not need their own ‘this’ context. This avoids them for object methods or when a constructor function is needed.

Updated on September 13, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved