Arrow Functions

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

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.


References


Backlinks