Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
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.
When can we omit return in arrow functions?
10.2.
Does an arrow function have a prototype property? 
10.3.
Where are arrow functions often used?
10.4.
How to make arrow functions in JavaScript asynchronous?
10.5.
Why can arrow functions not be used as generators?
11.
Conclusion
Last Updated: Mar 27, 2024
Easy

Arrow Functions in JavaScript

Author Sagar Mishra
2 upvotes

Introduction 

Hey Ninjas! You must have heard the term JavaScript. So, once you start coding in JavaScript, you will realize that functions play a vital role in JavaScript. Functions can be declared using the classical regular functions way or with the help of arrow functions. 

Arrow functions in JavaScript

Our today's topic for this blog is Arrow functions in JavaScript. Let's take a closer look at the Arrow functions in JavaScript. If you are new to JavaScript, it is suggested to go through the JavaScript functions, and you can also 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 of a regular function.

// Declaring and calling a regular function

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

hello();


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();


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();


Output:

error message

However, the following code works perfectly fine:

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

hello();


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());


Output:

No Arguments output

 

Note: The above code is the same as,

// Arrow functions with no arguments

const result = () => {
   return 20;
}
console.log(result());


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));


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));


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));


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();


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();


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);


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);


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


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"));


Output:

Object Literals output
// Object literal setter using arrow functions

const setStudentDetail = (rollNo, name) => ({ rollNo: rollNo, name: name });
console.log(setStudentDetail(1, "Sapna"));


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

When can we omit return in arrow functions?

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, we have to use return explicitly when there are curly brackets.

Does an arrow function have a prototype property? 

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.

Where are arrow functions often used?

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

How to make arrow functions in JavaScript asynchronous?

We can make an arrow function asynchronous by using async/await.

Why can arrow functions not be used as generators?

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

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