Thought leadership from the most innovative tech companies, all in one place.

How To Convert Any Function To An Arrow Function In JavaScript

Same results, less code. Learn the process of converting any type of traditional JavaScript function into an arrow function to make your code more compact and powerful.

image

When it comes to JavaScript, it is no secret that it is a function heavy language. It is full of different ways of using, reusing, passing around functions and more.

And all of this is for a good reason. Functions provide a highly modular way of structuring your application logic. If you change something about your function, you only change the transformation that is happening to the given data.

This data isolation not only makes it easy to write applications, but it also makes your code more testable and robust. Because no matter where and when you run your code, as long as you provide the same inputs, you will receive the same outputs, regardless of your running environment or other variables.

If you want to have access to more tutorials like this, you can become a Medium member through the link below. If you choose to become a member through the link, a part of the membership fee will also support tutorials like this one, at no additional cost to you. Join Medium with my referral link - Doga Ozgon *As a Medium member, a portion of your membership fee goes to writers you read, and you get full access to every story…*dogaozgon.medium.com

One of the most popular front end libraries, React.js, also introduced something called “Hooks” with React 16.8 to allow front end developers to only use functional programming while developing user interfaces. This change is not minor in any way, as it changed the way you can think about creating user interfaces along with making the overall file structure much more modular and reusable.

When developing the front end of a web application with React.js, there are many times where you find yourself needing a function, but you only need it once. And sometimes these functions are so short that defining and using them with names can feel like writing clunky code. This can be the case, especially if you already know that you can make your code much more concise and legible.

But how do you make your functions much more compact, while keeping them equally easy to understand the next time you come to look at your code?

Arrow functions to the rescue

The power of arrow functions really shine when they are used in other functions which is a quite common thing to do in React.js. This is applicable when we only need a function to pass into another major function.

This modular way of writing our code also makes it easy to make changes with less possibility for bugs. Let’s first see an example code on arrow functions and then explain how we get there step by step, line by line.

const someNumbers = [1, 2, 3, 4];

Assume we have a simple array and we want to console.log another array that has double the value of every item in the array. With traditional functions in JavaScript, we can achieve this with the code below:

//Using traditional functions

function double(num1){

return num1 * 2;

}

console.log(someNumbers.map(double));

However if we were to use arrow functions, we could achieve the same results with the following code:

// Using an arrow function

console.log(someNumbers.map(num1 => num1 * 2));

With traditional functions:

  1. We first have to write the keyword “function” to tell javascript that we want to define a function.

  2. Then we give the function a name in order to be able to reuse it later.

  3. Then we open and close parentheses around the function argument.

  4. Then we open and close curly braces around the function body.

  5. Then we write the “return” keyword to denote what we want to return from that function body.

  6. And now, we can finally pass the function name to the console.log so that we can perform the functionality that we want to perform. In this case this is doubling every number in a given array and console logging the output.

With arrow functions; however, the process is much simpler. We can directly write it inside the console log and they will simply perform their functionality.

The first thing you should know about arrow functions is that we should see the arrow sign which composes of an equal sign, right next to a greater sign. Like this one: “=>” note that there should be no spaces between these characters. On the left side of this arrow sign, we will have the function arguments and on the right side of it we will define the function body.

When we convert a traditional javascript function into an arrow function we can use the following steps:

  1. We can start with the traditional function and we can remove the function keyword along with the function name. Then we can add the arrow sign between the arguments and the function body.

  2. On the left side of the arrow: If there is a single argument, then we can remove the parentheses around it. If we have multiple arguments or no arguments at all, then we should keep the parentheses.

  3. For the right side of the arrow: If the function only returns an expression, then you can remove the “return” keyword along with the curly braces around the function body. In this case, the result of the expression will be automatically returned.

  4. If the returned expression is too large to fit in a single line, you can use parentheses around it. This is especially more commonly used in React.js development.

Following the steps above, you can fully convert your traditional function into an arrow function. Note that only the first step is necessary to convert a traditional function into a working arrow function.

However, it is quite common to apply 3 or even all 4 of these steps to end up with the most concise code with high legibility.

Let’s apply these steps to some traditional functions to successfully convert them to arrow functions. Starting with the function we converted above.

Also, as you have also probably noticed, we are using the map() method to apply the transformation, as in we are passing our function to map method to apply the transformation. The map method was introduced with ES6 along with some other highly useful methods. If you are not familiar with map, I highly recommend learning about it.

In a nutshell we apply the map() method to an iterable such as an array, and we pass it a function. Map takes the individual elements in the array we give it (in this case someNumbers) and applies the function transformation, and returns the results in an array. So it takes an array, applies the function, and returns the resulting array. In this case it takes in the someNumbers array, multiplies every array element by two, and returns the resulting array of doubled numbers. With that out of the way, let’s continue with our example:

//traditional function

function double(num1){
  return num1 * 2;
}

// apply step 1:
(num1) => {
  return num1 * 2;
}

// apply step 2:
num1 => {
  return num1 * 2;
}

// apply step 3:
num1 => num1 * 2;

// since we have a short function body, no need to apply step #4
// but we still can, and it will still work
num1 => (num1 * 2);

Let’s see couple more examples so we also cover other scenarios when converting traditional functions into arrow functions.

Example with multiple arguments:

// traditional function
function multiplyTwo(num1, num2) {
 return num1 * num2;
}

// first step applied
(num1, num2) => {
 return num1 * num2;
}

// second step applied
//(no change here, because we have multiple arguments)

(num1, num2) => {
 return num1 * num2;
}

// third step applied

(num1, num2) => num1 * num2;


// since we have a short function body, no need to apply step no 4
// but we still can, and it will still work
(num1, num2) => (num1 * num2);

Example with no arguments:

function sayHelloWorld(){
return "Hello, " + "World!";
}

// apply step 1:
() => {
return "Hello, " + "World!";
}

//apply step 2:
// no change here, because there is no arguments
// and we keep the parantheses as is

() => {
return "Hello, " + "World!";
}

// apply step 3:
() => "Hello, " + "World!";

// apply step 4:
// since we have a short function body, no need to apply step no 4
// but we still can, and it will still work
() => ("Hello, " + "World!");

Example with no arguments and a long returned expression:

//traditional function

function appendLoremIpsumText(){
return ("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." + "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
}

//apply step 1:
()=> {
 return ("Lorem ipsum dolor sit amet, consectetur adipiscing elit,       sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."     + "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do      eiusmod tempor incididunt ut labore et dolore magna aliqua.");
}

//apply step 2:
// no change here, since we had no arguments
()=> {
return ("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." + "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
}

//apply step 3:
()=> (
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." + "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
);

//apply step 4:
() => ("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." + "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");

Example function with a longer function body and a return statement:

//traditional function

function sayHi(name){
 const message = "Hi " + name;
 return message;
}

//apply step 1:
(name) => {
 const message = "Hi " + name;
 return message;
}

//apply step 2:
name => {
 const message = "Hi " + name;
 return message;
}

//apply step 3:
name => {
 const message = "Hi " + name;
 return message;
}

//apply step 4, (since the returned expression can fit easily into //one line no need to change anything here):

name => {
 const message = "Hi " + name;
 return message;
}

When applying the steps above, do not forget that you do not need to apply all four steps. Once you apply the first step you technically converted a traditional function to an arrow function. What I would recommend at this point is to try out some functions yourself and if you get stuck, you can always come here to check your steps and approach. Do not be afraid of making mistakes as this is how you will learn in many cases.

Conclusion

In this article, you have seen a step by step guide on how to convert any traditional JavaScript function to an arrow function along with working code examples. I hope you got some value out of this article and it helped you in one way or another. If you want more tutorials like this, you can follow me here on Medium.

If you have any questions about this tutorial, feel free to reach out or leave them as a comment here and I will get back to you as fast as I can, with an answer. With that said hope you got some value out of this article and I will see you in the next one.




Continue Learning