Arrow functions
Once you get comfortable with functions, you'll write them all the time. Arrow
functions are the compact version: same idea, fewer keystrokes. They arrived
with ES6 and use the => (arrow) symbol that gives them their name.
const add = (a, b) => {
return a + b;
};
Implicit return
If the function has only one expression, you can omit the braces and the
return keyword. The result is returned automatically:
const add = (a, b) => a + b;
const square = n => n * n; // a single parameter: parentheses optional
const greet = () => "Hello"; // no parameters: parentheses required
Be careful when returning objects
⚠️ Classic trap: to return an object literal directly, wrap it in parentheses.
If you don't, JavaScript thinks those braces are the function body and quietly
hands you undefined:
const createPoint = (x, y) => ({ x: x, y: y });
Arrow functions shine in the short functions you pass to array methods like
map or filter (coming up very soon). Get used to that arrow: you're going to
write a ton of them.
Examples
Three equivalent forms
const triple1 = function (n) { return n * 3; };
const triple2 = (n) => { return n * 3; };
const triple3 = n => n * 3; // the most compact one
console.log(triple1(2), triple2(2), triple3(2)); // 6 6 6