Arrow Functions in JavaScript

Zeeshan SafdarZeeshan Safdar
2 min read

Table of contents

Besides function declarations and function expressions, JavaScript also has another very concise syntax for defining a function. These functions are called arrow functions.

In this concept, we will focus on the syntax used to write an arrow function. There are differences in the way that an arrow function works, such as this binding.

Here is a comparison between a function declaration and an arrow function.

function addUpTwoNumbers(num1, num2) {
  return num1 + num2;
}

// function keyword removed and => added
const addUpTwoNumbers = (num1, num2) => {
  return num1 + num2;
};

Above, you will see that the arrow function syntax:

  1. removes the keyword function

  2. has declared the identifier addUpTwoNumbers as a const

  3. adds a fat arrow =>

If the function body contains only a return statement, like in the example above, the {} and the return keyword can be omitted.

const addUpTwoNumbers = (num1, num2) => { return num1 + num2 };

// can be shortened to
const addUpTwoNumbers = (num1, num2) => num1 + num2;
// braces {} and return removed

In the special case of only returning an object from an arrow function, parentheses are needed around the object to be able to omit the return statement.

// explicit return of object
const addUpTwoNumbers = (num1, num2) => {
  return { num1, num2 };
};

// implicit return of object
const addUpTwoNumbers = (num1, num2) => ({ num1, num2 });

The use of parenthesis around parameters depends on the number of parameters.

// one parameter does not need parenthesis
const square = num => num * num;

// two or more parameters need to be wrapped in parenthesis
const addUpTwoNumbers = (num1, num2) => num1 + num2;

Other concepts such as Rest Parameters and Destructuring can also be used with an arrow function.

Learn More

Credits: Exercism

1
Subscribe to my newsletter

Read articles from Zeeshan Safdar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Zeeshan Safdar
Zeeshan Safdar

An accomplished front-end developer with a strong background in creating visually stunning and user-friendly websites and web applications. My deep understanding of web development principles and user-centered design allows me to deliver projects that exceed client expectations. I have a proven track record of success in delivering projects on time and to the highest standards, and I am able to work well in a team environment and am always looking for new challenges to take on.