Arrow Function in JavaScript


In this tutorial, you will learn what is an arrow function, the benefits of the arrow function, and how to use it in JavaScript.

What is arrow function in JavaScript?

Arrow function is one of the features introduced in ES6 for writing better javascript.

Arrow function is similar to a function expression, but it does not have a name. It is written as a function expression with parenthesis.

The function expression is followed by an arrow (=>). The arrow function expression is followed by an expression, which is returned by the arrow function.

let message = (name) => {
  return `Hello ${name}`;
}

Arrow function in javascript is an alternative way to write a function with shorter and cleaner syntax than a regular function.

An arrow function is also called the fat arrow function.

arrow function in javascript

Syntax of arrow function

The syntax of the arrow function is similar to the syntax of a function expression, except that it does not have a name.

() => { ... } // no parameter
param1 => { ... } // one parameter
(param1, param2) => { ... } // multiple parameters

The above syntax shows a function with no parameters, a function with one parameter, and a function with multiple parameters.


Example of arrow function

Here are few examples of arrow functions in JavaScript.

Example 1:

Example

// basic arrow function
const add = (a, b) => { return a + b };
// calling function
console.log(add(5, 15));
Try It

In the above example 'add' is the name of the function, parenthesis holds arguments and curly braces contain statements of the function.

Example 2:

In the arrow function when there is only one statement then You can omit the parenthesis.

Example

let increment = a => { return a + 5; }
  
console.log(increment(5));
Try It

Example 3:

Example

const today = () => {
  const date = new Date();
  const hour = date.getHours();
  if (hour => 12) {
    console.log("PM");
  }
  else {
    console.log("AM");
  }
}
today();
Try It

Arrow Function Without return Keyword

Arrow function without return keyword is also possible.

Writing function with a single statement is even shorter with arrow functions.

In the above example, a + b is returned using the return keyword, but when there is only a single statement in the arrow function then you can omit the return keyword and remove curly braces ( {} ) and it still works in the same way.

Arrow function returns the value by default.

Example

// arrow function without return keyword
const add = (a, b) => a + b;
console.log(add(1, 2));

const multiply = (a, b, c) => a * b * c;
console.log(multiply(5, 3, 4));
Try It

Arrow Function with Single Argument

Arguments are wrapped up in parenthesis (), but when there is only 1 argument in the arrow function then you can omit parenthesis and write the only argument.

In the example below there is only one argument 'name' for the 'greeting function'.

Example

// removing parenthesis for a single argument
const greetings = name => "Hello " + name;
console.log(greetings("John"));
console.log(greetings("Jeany"));
Try It

Note: Removing parenthesis only works when there is only 1 argument.


Arrow Function with No Argument

When there is no argument in the arrow function then you can write arrow function in 2 different ways:

  1. Using parenthesis () before the arrow (=>) with no argument
  2. Using underscore ( _ ) replacing parenthesis

Example: with ()

const greet = () => "Hello World!";
console.log(greet());
Try It

Let's see another example that has underscore _ in the place of parenthesis.

Example: with _

// using an underscore in place of ()
const greet = _ => "Hello World!";
console.log(greet());
Try It

Javascript Arrow Function VS Function

An arrow function is very much different from a regular function. At some places, it is better to use the arrow function while at different places regular function is better.

Let's see the difference between arrow function and regular function for better understanding.

Arrow Function Regular Function
Syntax Syntax of arrow function is different from regular function, arrow function use ( => ) to create function The regular function does not use the arrow to create a function
Return Arrow function has implicit return, you need not use the return keyword to return in the function Regular function need return keyword to return
Duplicate parameters Duplicate parameters are not allowed in an arrow function When not using 'use strict' you can have duplicate parameters
Constructor An arrow function is not constructible, which means you can't use new to construct The regular function can use the new keyword to construct
value of this this in arrow function remains same, no matter from where and who invoked function In regular function, this keyword depends on how and where the function is invoked

this In Arrow Function

Javascript arrow function handles this differently.

In regular function, this represents the object that calls the function, like button, document, window, etc but this in arrow function represents only the object that defines the arrow function.

Let's see an example to understand the difference.

Example

let car = function (carName,speed) {
  this.carName = carName;
  this.speed = speed;
  this.info = function () {
    setTimeout(function () {
      console.log(this.carName + " runs at " + this.speed);
    }, 2000)
  }
}
let bmw = new car("BMW", 120);
bmw.info();
Try It

The output is "undefined runs at undefined". You got undefined because the callback function set in setTimeout for calling regular function and this means that this for the function is set to window object because this in regular function depends on who invoked the function.

So if somehow we could have referred this to the same object which defined the function then we can solve the problem.

This is what an arrow function can do. The this of arrow function refers to the object which defines it. See the example below to understand.

Example

let car = function (carName,speed) {
  this.carName = carName;
  this.speed = speed;
  this.info = function () {
    setTimeout(() => {
      // this represent the object which defines the function
      console.log(this);
      console.log(this.carName + " runs at " + this.speed);
    }, 2000)
  }
}
let bmw = new car("BMW", 120);
bmw.info();
Try It

The output is { carName: 'BMW', speed: 120 } which means that this in an arrow function is the object which defined the function.


Benefits of Arrow Function

Arrow function has the following benefits over regular function.


Frequently Asked Questions

  1. What does () => mean in JavaScript?

    It is the arrow function syntax. It is a function expression that returns a function.

  2. Why arrow functions are used?

    They are used when you want to avoid using the this keyword in the function. The this keyword is used to refer to the object that calls the function, like button, document, window, etc. But in the arrow function, this is the object which defines the function.


Conclusion

Arrow function is a very useful feature in Javascript. It is a very simple feature and it is very easy to understand. We have looked at the arrow function in detail with examples.