Arrow functions in JavaScript

Hari Sapna Nair
Last Updated: May 13, 2022

Introduction 

Once you start coding in JavaScript, you will realize that functions play a vital role in the JavaScript programming language. Functions can be declared using the classical regular functions way or with the help of arrow functions. 

 

Arrow functions in JavaScript were introduced in ES6, and it quickly became the favorite ES6 feature of the JavaScript community. Arrow functions in JavaScript provide developers with a helpful shorthand to write function expressions in JavaScript. Arrow functions provide a straightforward and concise syntax for creating functions that are often better than regular function expressions. This can save time, improve code readability, and they are so handy in React.
 

Let's take a closer look at the arrow functions in JavaScript in this blog. To understand arrow functions in JavaScript, it is essential to have prior knowledge of JavaScript functions, so please refer to our JavaScript-guided path.

Functions in JavaScript

JavaScript is based on functional programming. Hence, functions are fundamental building blocks of JavaScript. A function is a block of code that performs a specific task. Let's see an example for a regular function.
 

// Declaring a regular function named hello()
const hello = function () {
   console.log("Hello");
}

Arrow functions in JavaScript

Arrow functions in JavaScript is a concise alternative way to write regular functions in JavaScript). They are also called "fat arrow functions" as they use a fat arrow (=>). Owing to the usage of a fat arrow, it got its name arrow functions.
 

In arrow functions, instead of the function keyword, a fat arrow is used. Let's see how the above regular function can be written using the fat arrow function.
 

// Declaring an arrow function named hello()
const hello = () => {
   console.log("Hello");
}

 

JavaScript does not allow a line break between the parameter definition and the fat arrow in an arrow function. For example,

 

const hello = ()
=> {
   console.log("Hello");
}

hello()

 

Error

However, the following code works perfectly fine:
 

const hello = () =>
{
   console.log("Hello");
}

hello() // Hello

No arguments

If an arrow function doesn't take any argument, then use empty parentheses. For example,
 

// Arrow functions with no arguments
const result = () => 20

 

Note: The above code is the same as,
 

// Arrow functions with no arguments
const result = () => {
   return 20
}

One argument

If an arrow function has only one argument, then we can omit the parentheses. For example,
 

// Arrow function with one argument
const result = num => num + 5

Multiple arguments

If an arrow function has more than one argument, then we cannot omit the parentheses. For example,
 

// Arrow function with multiple arguments
const result = (num1, num2) => num1 + num2

Multiline arrow function

If an arrow function has multiple statements in the code block, then we cannot omit the curly braces and return keyword. For example,

 

// Multiline arrow function
const result = (num1,num2) => {
   let total = num1 + num2;
   return total;
}

this and Arrow functions in JavaScript

Inside a regular function, this keyword refers to the function where it is called. However, when this keyword is used with the arrow function, it refers to its parent scope. This happens because the arrow function doesn't define its own execution context and does not have its own this.

 

Let's look at an example for a better understanding.

 

// Regular function
function Student() {
   this.name = 'Sapna',
   this.introduce = function () {
       // Here this is accessible
       console.log(this.name);
       function innerIntroduceFunc() {
           // Here this refers to the global object
           console.log(this.name);
       }
       innerIntroduceFunc();
   }
}

let s = new Student();
s.introduce();

 

Output:

Sapna
undefined

 

Here, this.name inside this.introduce() is accessible because this.introduce() is the method of an object.

 

However, innerIntroduceFunc() is a normal function, and this.name is not accessible because this refers to the global object. Hence, this.name inside the innerFunc() function gives undefined.
 

// Arrow function
function Student() {
   this.name = 'Sapna',
   this.introduce = function () {
       console.log(this.name);
       // this refers to parent scope
       let innerIntroduceFunc = () => {
           console.log(this.name);
       }
       innerIntroduceFunc();
   }
}

const s = new Student();
s.introduce();

 

Output:

Sapna
Sapna

 

Here, the innerIntroduceFunc() is defined using the arrow function. So, this refers to the parent's scope. 

Argument Binding

Regular functions in JavaScript have arguments binding. Due to this, we can access the arguments passed using the arguments keyword. 

 

However, arrow functions in JavaScript do not have arguments binding. So, when we try to access an argument using the arrow function in JavaScript, it will give us an error. For example,
 

let func = () => {
   console.log(arguments);
}

func(1,2,3);

 

Error

 

To solve this issue, we can make use of the spread operator.

 

let func = (...arguments) => {
   console.log(arguments);
}

func(1,2,3);

 

Output:

[ 1, 2, 3 ]

Arrow Function with Promises and Callbacks

While writing promises and callbacks, arrow functions provide a better syntax. For example, 
 

// Regular function
asynchronousFunction().then(function() {
   return asynchronousFunction1();
}).then(function() {
   return asynchronousFunction2();
}).then(function() {
   finish;
});

 

This can be written in a much simpler way using arrow functions.
 

// Arrow functions
asynchronousFunction()
.then(() => asynchronousFunction1())
.then(() => asynchronousFunction2())
.then(() => finish);

Object Literals

We can use the arrow functions to declare setter functions and set the value of object literals effortlessly. Let's look at an example.

 

// Object literal setter using regular functions
const setStudentDetail = function(rollNo, name) {
   return {
       rollNo: rollNo,
       name: name,
   }
}

console.log(setStudentDetail(1,"Sapna"));


// Object literal setter using arrow functions
const setStudentDetail = (rollNo, name) => ({ rollNo: rollNo,name:name,
});

console.log(setStudentDetail(1, "Sapna"));

 

Output:

{ rollNo: 1, name: 'Sapna' }

Benefits of using Arrow functions in JavaScript

Some of the benefits of using arrow functions in JavaScript are as follows:-

  • Arrow functions have shorter syntax than regular function expressions.
  • Arrow functions have implicit return statements.
  • Arrow functions increase readability.

Limitations of using Arrow functions in JavaScript

Some of the limitations of arrow functions are as follows:-

  • Arrow functions are anonymous and can be harder to debug. However, we can assign them to a variable for more clarity.
  • Arrow functions cannot be used as constructors.
  • Arrow functions do not have new.target keyword.
  • Arrow functions do not have their own bindings to this or super and should not be used as methods.
  • We usually cannot use an arrow function as a method.
  • Arrow functions cannot be used as a generator function.
  • The call, apply and bind methods cannot be used with arrow functions.

Frequently Asked Questions

1. When can we omit return in arrow functions?

Ans:- Return can be omitted when there are no curly brackets. This is because arrow functions use implicit returns when written without curly brackets. In contrast, when there are curly brackets, we have to use return explicitly.

 

2. Does an arrow function have a prototype property? 

Ans:- The function has the prototype property when a function is defined by the regular method using a function keyword. However, arrow functions in JavaScript don't have the prototype property.

 

3. Where are arrow functions frequently used?

Ans:- Arrow functions are frequently used in promise chaining, callback chaining, array methods, and situations where anonymous functions would be useful.

 

4. How to make arrow functions in JavaScript asynchronous?

Ans:- We can make an arrow function asynchronous by using the async/await.
 

5. Why can arrow functions not be used as generators?

Ans:- We cannot use the yield keyword within an arrow function's body. Hence, arrow functions cannot be used as generators.

Key Takeaways

This blog covered the basic concepts of arrow functions in JavaScript in detail and various examples and frequently asked questions. 


Don't stop here. Check out our Basics of JavaScript - guided path to learn JavaScript from scratch. If you are preparing for JavaScript Interviews, check out the blog Javascript Interview Questions.

 

We hope you found this blog useful. Liked the blog? Then feel free to upvote and share it.

Was this article helpful ?
1 upvote

Comments

No comments yet

Be the first to share what you think