In 2015, JavaScript introduced a shorter way to write function expressions, called arrow functions. They're called that because they use an arrow => (an equals sign followed by a greater-than sign):
const square = (number) => {
return number * number;
};
console.log(square(6));
It prints
36
So far, we've just swapped the word function for an arrow after the parentheses. But it gets better. If the body is just a single return statement, you can drop the curly braces and the word return:
const square = (number) => number * number;
const add = (a, b) => a + b;
const sayHi = () => "Hi there!";
const shout = (text) => text.toUpperCase() + "!!!";
console.log(square(7));
console.log(add(2, 3));
console.log(sayHi());
console.log(shout("arrow functions are cool"));
It prints
49 5 Hi there! ARROW FUNCTIONS ARE COOL!!!
This is called an implicit return: the value after the arrow is automatically returned. Short and sweet!
Here's a side-by-side comparison of the same function written four ways:
// 1. Function declaration
function double(n) {
return n * 2;
}
// 2. Function expression
const double = function (n) {
return n * 2;
};
// 3. Arrow function with a body
const double = (n) => {
return n * 2;
};
// 4. Arrow function with an implicit return
const double = (n) => n * 2;
All four do exactly the same job (though you couldn't put them all in the same file, because they all use the name double).
If you use curly braces in an arrow function, the implicit return goes away, and you must write return yourself:
const triple = (n) => { n * 3 };
console.log(triple(4));
It prints
undefined
The curly braces turned it into a normal function body, and that body has no return, so you get undefined. Either remove the braces ((n) => n * 3) or add return ((n) => { return n * 3; }).
Which style should I use?
Honestly, it's mostly a matter of taste, and you'll see all of them in real code. Here's a sensible approach:
- Use function declarations for your main, named functions, the "big" building blocks of your program.
- Use arrow functions for short, simple functions, especially when you pass a function into another function (you'll do this a lot in Grade 10).
Arrow functions aren't exactly the same as regular functions. The main difference involves a special keyword called this, which we'll meet in Grade 8 and fully understand in College. For now, both kinds work identically for everything you'll write.