Arrow Functions
Arrow functions simplify the syntax of our traditional functions.
They use symbols that make intuitive sense to help make our functions simpler.
The old way of writing functions:
const add = function(a, b){
return a + b;
}
With arrow functions, we can remove the function key word, and add an arrow comprised of =
and >
.
const add = (a, b) => {
return a + b;
}
Cool, our function is already simpler. This syntax makes sense. It's like saying "I'm going to take a and b and transform them." Right? And arrow suggests transportation, transformation, forwarding, moving, etc. "I'm going to take a and b and 'arrow' them."
But wait, there's more!!
We can simplify it some more. If your function has a single expression. Or a single line of code in the function, you can remove the curly brackets and return
keyword
const add = (a, b) => a + b;
This is called an implicit return.
The rule is, if you have a just one expression in your function, remove both the curly brackets and the return
keyword.
If you only have one argument, you can also drop the parentheses!
const double = (num) => num * 2;
can be written:
const double = num => num * 2;
If there are zero arguments, you need the parentheses.
const logHello = () => console.log("hello");
Arrow functions start to look especially sexy when used as anonymous callback functions.
const numbers = [1, 2, 3]
numbers.map(function(number) {
return 2 * number;
});
can be:
const numbers = [1, 2, 3]
numbers.map(number => 2 * number);
This is possible because we are using arrow functions and .map()
instead of a for loop.