How to rewrite a standard function to an arrow function in Js?

The arrow function is a feature in the ES6 version of Javascript that provides an easy and compact structure to write functions in javascript. It allows the creation of functions without declaring the function’s name and using the return keyword. However, they are not created to replace the standard way of creating functions, as arrow functions have some limitations.

Arrow functions are very useful when writing inline javascript functions within other functions. They are also very useful when working with React hooks, and when you are using some array functions like map(), filter() and reduce().

This article will focus on converting a standard function into an arrow function in javascript in less than 4 easy steps.

How to convert a NorMAL function to an arrow function

To convert a standard function to an arrow function in javascript, you will need to follow these steps:

  • Remove the ‘function’ keyword and the function’s name. For example, in the following code below:
//The standard function
function printUser(userName) {
  return ( console.log(userName));
}

//Remove the function name and 'function' Keyword
(userName) {
  return ( console.log(userName));
}
  • Add the arrow function syntax “ = > ‘ after the parameter parentheses, as shown in the code below:
//The standard function
function printUser(userName) {
  return ( console.log(userName));
}

//add the => syntax
(userName) => {
  return ( console.log(userName));
}
  • Remove the return keyword and curly braces from the function
//The standard function
function printUser(userName) {
  return ( console.log(userName));
}

//Remove the return keyword and curlybraces
(userName) => console.log(userName) ;

  • Remove the parentheses around the parameter.
//The standard function
function printUser(userName) {
  return ( console.log(userName));
}

//Remove the parenthesis around the pareameter
userName => console.log(userName) ;

Note: In some cases, you can remove the parentheses around the parameter and the curly braces that cover the function body. When the function has multiple parameters, you must keep the parentheses when there are no parameters or destructured, default, or rest parameters.

Take the multiply function below as an example.

// Traditional multiply function
(function multiply (a, b) {
  return a * b;
});

// Arrow function
(a, b) => a * b;

const a = 10;
const b = 6;

// Traditional multiply function with no parameters
(function multiply () {
  return a * b;
});

// Arrow function with no arguments)
() => a * b;

That’s all you need to know about changing a traditional function to an arrow function in javascript. Learn about how to convert an arrow function back to a standard javascript function