Table of contents
1.
Introduction 
2.
Functions in JavaScript
3.
Arrow Functions in JavaScript
3.1.
No Arguments
3.2.
Passing One Argument
3.3.
Passing Multiple Arguments
3.4.
Multiline Arrow Function
4.
Using this keyword
5.
Argument Binding
6.
Promises and Callbacks
7.
Object Literals
8.
Advantages
9.
Limitations
10.
Frequently Asked Questions
10.1.
What is an arrow function in JavaScript?
10.2.
What does the => mean in JavaScript?
10.3.
When should I use arrow functions in JavaScript?
11.
Conclusion
Last Updated: Sep 27, 2024
Easy

Arrow Functions in JavaScript

Author Sagar Mishra
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction 

Arrow functions, introduced in ECMAScript 6, provide a concise syntax for writing function expressions in JavaScript. They allow you to define anonymous functions using a more compact syntax, omitting the `function` keyword. Arrow functions automatically bind `this` to the surrounding code's context, making them useful for writing shorter, more readable code, especially when working with callbacks and higher-order functions. In this article, we will discuss this in detail.

Arrow functions in JavaScript

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 of a regular function.

// Declaring and calling a regular function

const hello = function () {
    console.log("Hey Ninjas!");
};

hello();
You can also try this code with Online Javascript Compiler
Run Code


Output:

output of example

Arrow Functions in JavaScript

Arrow functions in JavaScript are a concise alternative way to write regular functions in JavaScript. They are also called "fat arrow functions" as they use a fat arrow (=>). It got its name arrow functions due to using a fat arrow.

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 and calling an arrow function

const hello = () => {
    console.log("Hey Ninjas!");
}

hello();
You can also try this code with Online Javascript Compiler
Run Code


Output:

Arrow Functions output

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("Hey Ninjas!");
}

hello();
You can also try this code with Online Javascript Compiler
Run Code


Output:

error message

However, the following code works perfectly fine:

const hello = () => {
    console.log("Hey Ninjas!");
}

hello();
You can also try this code with Online Javascript Compiler
Run Code


Output:

Arrow Functions output

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; 
console.log(result());
You can also try this code with Online Javascript Compiler
Run Code


Output:

No Arguments output

 

Note: The above code is the same as,

// Arrow functions with no arguments

const result = () => {
   return 20;
}
console.log(result());
You can also try this code with Online Javascript Compiler
Run Code


Output:

No Arguments output 2

Passing One Argument

We can omit the parentheses if an arrow function has only one argument. For example,

// Arrow function with one argument

const result = num => num + 5;
console.log(result(10));
You can also try this code with Online Javascript Compiler
Run Code


Output:

Passing One Argument output

Passing Multiple Arguments

We cannot omit the parentheses if an arrow function has more than one argument. For example,

// Arrow function with multiple arguments

const result = (num1, num2) => num1 + num2;
console.log(result(10, 5));
You can also try this code with Online Javascript Compiler
Run Code


Output:

Passing Multiple Arguments output

Multiline Arrow Function

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

// Multiline arrow function

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

console.log(result(10, 5));
You can also try this code with Online Javascript Compiler
Run Code


Output:

Multiline Arrow Function output

Using this keyword

Inside a regular function, the 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();
You can also try this code with Online Javascript Compiler
Run Code


Output:

this keyword output

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);
       
       // Keyword ‘this’ refers to parent scope
       let innerIntroduceFunc = () => {
           console.log(this.name);
       }
       innerIntroduceFunc();
   }
}

const s = new Student();
s.introduce();
You can also try this code with Online Javascript Compiler
Run Code


Output:

innerIntroduceFunc output

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 gives us an error. For example,

let func = () => {
   console.log(arguments);
}
func(1,2,3);
You can also try this code with Online Javascript Compiler
Run Code


Output:

Argument Binding error

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

let func = (...arguments) => {
   console.log(arguments);
}
func(1,2,3);
You can also try this code with Online Javascript Compiler
Run Code


Output:

Argument Binding output

Promises and Callbacks

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

const ninjaTest = async () => {
  return "Hello";
}

ninjaTest().then(
  function (value) {
    console.log("Success!");
  },
  function (error) {
    console.log("Error!");
  }
);
You can also try this code with Online Javascript Compiler
Run Code


Output:

Promises and Callbacks output

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"));
You can also try this code with Online Javascript Compiler
Run Code


Output:

Object Literals output
// Object literal setter using arrow functions

const setStudentDetail = (rollNo, name) => ({ rollNo: rollNo, name: name });
console.log(setStudentDetail(1, "Sapna"));
You can also try this code with Online Javascript Compiler
Run Code


Output:

Object Literals output

Advantages

Advantages

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

Limitations

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 don't have their own bindings to this or super. Also, they 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.
     

Check out this article - Balanced Parentheses and Fibonacci Series in JavaScript

Frequently Asked Questions

What is an arrow function in JavaScript?

An arrow function in JavaScript is a concise way to write function expressions, using the => syntax, which simplifies function scoping and syntax.

What does the => mean in JavaScript?

The => symbol in JavaScript defines an arrow function, creating a function with a shorter syntax and lexically binding this value.

When should I use arrow functions in JavaScript?

Use arrow functions in JavaScript for concise function expressions, when you need lexical scoping of this, and where function hoisting is not required.

Conclusion

This article discusses the topic of Arrow functions in JavaScript. In detail, we have seen the definition of arrow functions, this keyword, argument binding, promises and callbacks, Object literals, advantages and limitations.

We hope this blog has helped you enhance your knowledge of Arrow functions in JavaScript. If you want to learn more, then check out our articles.

And many more on our platform Coding Ninjas Studio.

Refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio!

But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundles for placement preparations.

However, you may consider our paid courses to give your career an edge over others!

Happy Learning!

Live masterclass