Arrow Function in JavaScript | Example Program

Arrow function is the feature introduced in the ES6 version of JavaScript. It enables us to create functions in a cleaner and shorter way compared to normal functions.

For example, this normal function

// Function expression
   let sum = function(num1, num2) {
     return num1 + num2;

can be written as using an arrow function.

// Using arrow functions
   let sum = (num1, num2) => num1 + num2;

As you can observe in the above example, there is no function keyword used in arrow function. We have also omitted return keyword from the body of function. Hence, arrow function supports an even more compact syntax in JavaScript.

JavaScript Arrow Function Syntax

The general syntax of the arrow function in JavaScript is as:

let myFunction = (parameter-list) => {

In the above syntax, myFunction is the name of variable. Since arrow function is always anonymous in JavaScript, we must assign it to a variable, as we did with function expressions.

The example above shows we have created an arrow function that’s assigned to a variable myFunction.

Arrow function definition starts with a comma-separated list of parameters in parentheses, followed by the fat-arrow (=>), followed by the function body in curly braces.

If there is no parameter, or more than one parameter, the list of parameters must be enclosed within parentheses. But, we have only a single parameter, we can omit parentheses.

  • No parameters: ( ) => {. . . }
  • One parameter: x => {. . . }
  • More than one parameter: (x, y) => {. . .}

A mandatory fat-arrow operator (=>, an equal sign immediately followed by a greater than sign) tells JavaScript interpreter that we are dealing with arrow function.

If the function body has a single statement or expression, we can write arrow function as:

let myFunction = (parameter-list) => expression;

JavaScript Arrow function can return a value directly without using return keyword, by omitting the { } immediately after (=>) arrow. When using arrow function, we do not need to write return keyword if the body of function contains just one line of code.

How to call Arrow Function in JavaScript?

We can call arrow function in exactly the same way as we do regular function. Just write its name and do not forget to add parentheses at the end. We can also pass argument values to parameter-list of arrow function. The general syntax is like this:


Arrow Function with No Argument

If arrow function doesn’t have any argument, then you should write an empty pair of parentheses. For example:

Program code 1:

   <title>Arrow functions with no arguments</title>
// First arrow function declaration.
   let greeting = () => document.write("Hello JavaScript", "<br>");
   greeting(); // calling arrow function.

// Second arrow function declaration.
   const constantFunc = () => 50;
   document.write(constantFunc()); // calling arrow function.
     Hello JavaScript

Arrow Function with One Parameter

If arrow function has exactly one parameter, we can omit the parentheses around the parameter list. Let’s understand with the help of examples.

Program code 2:

   <title>Arrow functions with one parameter</title>
// First arrow function with one parameter.
   let name = firstName => document.write(firstName, "<br>");
   name("Tripti"); // calling arrow function with passing argument value.

// Second arrow function with one parameter.
   let polynomial = x => x*x + 2*x + 10;
   document.write(polynomial(5)); // calling arrow function with passing argument.

Arrow Functions with Multiple Parameters

We can define a function with more than one parameter. Let’s take an example program based on it.

Program code 3:

  <title>Arrow functions more than one parameter</title>
   let sum = (x, y) => x + y;
   document.write(sum(2, 3), "<br>");

   let sub = (x, y, z) => x - y - z;
   document.write(sub(4, 5, 6), "<br>");

   let multiply = (x, y, z) => x * y * z;
   document.write(multiply(4, 5, 6));

Arrow Function as an Expression

We can also create dynamically an arrow function and use it as an expression. Let’s write a JavaScript program in which we will take age from the user as input and check that you are eligible for the vote or not.

Program code 4:

  <title>Arrow function as an expression</title>
  let age = prompt("Enter your age:");
  let vote = (age >= 18) ?
   () => document.write('You are eligible to vote.') :
   () => document.write('You are not eligible to vote.');
  vote(); // calling function.

Here, we have entered age 18 in the dialog box and the following output will display on the web browser.

      You are eligible to vote.

Multiple Statement inside Arrow Function

If the body of arrow function contains multiple statements, we need to put them inside curly brackets {}. For example:

Program code 5:

   <title>Multiple statements inside arrow function </title>
   let s = (a, b, c) => {
     let sum = a + b + c;
     return sum;
  let sum2 = s(10, 20, 30);
  document.write("Sum: " +sum2);
     Sum: 60

Return Object Literal using Arrow Function

If you return object literal using arrow function, you need to put the object literal inside the parentheses to avoid syntactic ambiguity between the curly braces of the function body and the curly braces of object literal.

If you do not do this, JavaScript interpreter does not understand the difference between an object literal and a code block. Therefore, by enclosing object with parentheses, the object will return, even if we do not use return keyword explicitly.

Let us take an example program based on the above concept.

Program code 6:

   <title>Returning Object literal using Arrow function </title>
// ES5:
   let per = function person(firstName, id)
     return {
        name: firstName,
        id: id
  let p = per("John", 12464);
  document.write("Name: " ", "+"Id: ", "<br>");

// ES6:
// Method 1:
   let person = (firstName, id) => { return {name: firstName, id: id};};
   let x = person("Tripti", 12345);
   document.write("Name: " ", "+ "Id: ", "<br>");

// Method 2:
   let person2 = (firstName, id) => ({name: firstName, id: id});
   let y = person2("Deepak", 54647);
   document.write("Name: " ", " +"Id: ";
     Name: John, Id: 12464
     Name: Tripti, Id: 12345
     Name: Deepak, Id: 54647

Array of Objects using Arrow Function

Let’s take a simple array of objects:

const smartPhones = [
      {name: 'Iphone 13 Pro', Price: 676},
      {name: 'Samsung Galaxy S13', Price: 685},
      {name: 'Vivo Y21', Price: 345}

Here, we have created an array of objects with just names and prices in ES5. Now, we will map the above array of objects and display prices on the web browser.

// ES5:
let prices = {
    return smartPhone.Price;
document.write(prices); // 676,685,345

An arrow function in JavaScript ES6 is more concise and easier to read and map an array of objects. Look at the code below to understand better.

// ES6:
let prices = => smartPhone.Price);

Arrow Function with Promises and Callbacks

Arrow functions in JavaScript provide concise and better syntax to write promises and callbacks. Consider the following example code.

// ES5
  asyncFunct().then(function() {
     return asyncFunct1();
  }).then(function() {
     return asyncFunct2();
  }).then(function() {

In ES6, we can write the above code more simplified and arguably easier to read using arrow function.

// ES6
   .then(() => asyncFunct1())
   .then(() => asyncFunct2())
   .then(() => finish);

Can Arrow functions be used to create Constructor functions?

We cannot use an arrow function to create a constructor function as arrow function has not its own this. So, whenever we invoke this, it refers to its parent scope. For example,

let Doomed = () => { };
let d = new Doomed(); // TypeError: Doomed is not a constructor.

The main purpose of a constructor function is to set properties in the newly created object, which we pass to the function using this keyword.

If the function does not have its own this, it cannot set properties on the new object. Therefore, it doesn’t make any sense to use for creating a constructor function.

Can we use arrow functions to create method inside object?

No, we cannot use arrow functions to construct method inside object.

let person = {
     name: 'John',
     age: 30,
     sayName: () => {
      // Here, this refers to the global .....
  person.sayName(); //output: undefined.

In this tutorial, you learned the concept of arrow function in JavaScript with various examples. Arrow functions are powerful, concise, and developers love them to use in JavaScript coding.

Perhaps you should use it in ES6. Hope that you will have understood the basic concept of arrow function with example.
Thanks for reading!!!
Next ⇒ Objects in JavaScript⇐ Prev Next ⇒