In JavaScript, there are three ways to write a function. We have function declarations, function expressions, and arrow function expressions. Which should you use? What's the difference? So many questions! 🤯

Function declarations

A function declaration starts with the function keyword, like so:

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

This is my personal favourite for readability.

Function expressions

You create a function expression by assigning an anonymous function to a variable, thereby making it a named function. Unlike function declarations, these should end with a semicolon:

var add = function (num1, num2) {
return num1 + num2;
};

What's the difference?

In short: hoisting.

Function declarations are hoisted. Function expressions are not hoisted.

My friend Chris Ferdinandi has an excellent post about this:

What is hoisting in vanilla JavaScript?

Which should you use?

Whether you use function declarations or function expressions is almost entirely down to personal preference.

Arrow function expressions

Arrow function expressions are a shorter way of writing functions. First introduced in ES6, they work in all modern browsers. If you need to support Internet Explorer, you have to transpile your code using Babel.

The most verbose arrow function looks like this. You drop the function keyword and add a fat arrow (=>) after the parameters:

var add = (num1, num2) => {
return num1 + num2;
};

If your function just returns a value, you can use an implict return statement. This means you can drop the return keyword and the curly braces ({}), then move everything onto a single line (although it doesn't have to be a single line).

Some people like the brevity, but I personally think this is quite unreadable:

var add = (num1, num2) => num1 + num2;

If the function only has a single parameter, you can even remove the parentheses () around the parameter:

var double = num => num * 2;

It's important to know that arrow functions change the behaviour of this, arguments, super, and new.target. This can be helpful, but your code might behave differently to how you would expect.

Check out Arrow function expressions in the MDN Web Docs.