How to convert a function declaration to an arrow function

Posted on 24 January 2023

JavaScript Beginner Functions

I've got you covered with 5 simple steps.


Introduction

This is our starting point, a function declaration that takes in two values and returns their total.

function add(a, b) {
    const total = a + b;
    return total;
}

Step one

Add variable and remove function name.

const add = function (a, b) {
    const total = a + b;
    return total;
};

Step two

Convert to arrow, remove function keyword and place fat arrow to the right of the parentheses.

const add = (a, b) => {
    const total = a + b;
    return total;
};

Step three

Remove return and total variable.

const add = (a, b) => {
    return = a + b;
};

Step four

Place on one line.

const add = (a, b) => { return = a + b; };

Step five

Remove function block and return keyword.

const add = (a, b) => a + b;

Conclusion

Not as scary as you thought right?

However there are subtle differences between the two functions and reasons why you might choose one over the other. I hope to write about that soon.

Want to carry on reading? Discover more blog posts.