Arrow Functions
Arrow functions are a shorter way to write a function, and the short form is why they appear everywhere in modern JavaScript.
An arrow drops the function keyword. A single expression body returns automatically, so no braces and no return are needed. Arrows are ideal as arguments to other functions and unsuitable as object methods.
EXERCISE
1The Same Function, Written Shorter
An arrow function does the same job as a function expression with less ceremony, and the savings add up fast.
Step by step, from long to short:
// A function expression
const double = function (n) {
return n * 2;
};
// An arrow function: drop the keyword, add =>
const double2 = (n) => {
return n * 2;
};
// One expression? Drop the braces and the return.
const double3 = (n) => n * 2;
console.log(double3(5)); // 10
That last step is called an implicit return:
const square = (n) => n * n;
const isAdult = (age) => age >= 18;
const greet = (name) => `Hello, ${name}`;
console.log(square(4)); // 16
console.log(isAdult(20)); // true
console.log(greet("Ada")); // Hello, Ada
Braces mean you are back to writing return yourself:
const withBraces = (n) => { n * 2 };
console.log(withBraces(5)); // undefined <- no return statement!
const fixed = (n) => { return n * 2; };
console.log(fixed(5)); // 10
Parameters, with and without brackets:
const noArgs = () => "nothing in"; // empty brackets required
const oneArg = (n) => n * 2; // brackets optional for exactly one
const oneArgBare = n => n * 2; // also legal
const twoArgs = (a, b) => a + b; // brackets required
console.log(twoArgs(2, 3)); // 5
The implicit return is the whole point. (n) => n * 2 says "take n, give back n times two" with nothing else in the way, which is why arrow functions took over the places where a function is passed as an argument. The moment you add braces you have opted back into writing return, and forgetting it is the single most common arrow function bug.
EXERCISE
2Returning an Object, and Other Sharp Edges
Two small syntax traps catch almost everyone the first time, and both have a one-character fix.
Returning an object literal needs brackets around it:
const makeUser = (name) => { name: name };
console.log(makeUser("Ada")); // undefined
// JavaScript read those braces as a FUNCTION BODY,
// and `name:` as a label. Wrap the object in round brackets:
const makeUser2 = (name) => ({ name: name });
console.log(makeUser2("Ada")); // { name: 'Ada' }
An arrow has no name of its own:
function declared() {}
const assigned = () => {};
console.log(declared.name); // "declared"
console.log(assigned.name); // "assigned" <- taken from the variable
// Passed straight in, it is anonymous, which shows up in stack traces:
[1, 2].forEach(() => { throw new Error("boom"); });
// The error reports an anonymous function.
Arrows cannot be called before they are defined:
console.log(early(2)); // 4
function early(n) {
return n * 2;
}
console.log(late(2)); // ReferenceError: Cannot access 'late' before initialization
const late = (n) => n * 2;
Multi-line implicit returns work, with brackets:
const describe = (user) => (
`${user.name} is ${user.age} years old ` +
`and lives in ${user.city}`
);
console.log(describe({ name: "Ada", age: 36, city: "London" }));
// Ada is 36 years old and lives in London
Pro Tip:
=> ({ ... })is worth memorising as a single unit of syntax. It is how you return an object from a concise arrow, it comes up constantly the moment you start transforming arrays of data, and the failure mode isundefinedrather than an error, which makes it hard to spot when you do not know the rule.
EXERCISE
3Where Arrows Fit and Where They Do Not
Arrows are the right choice for short functions passed to other functions, and the wrong choice for methods on an object.
Where they shine: as an argument to another function:
const numbers = [1, 2, 3, 4];
// The long form:
const doubled = numbers.map(function (n) {
return n * 2;
});
// The arrow form, which is why arrows exist:
const doubled2 = numbers.map((n) => n * 2);
console.log(doubled2); // [2, 4, 6, 8]
You have not met map yet; Unit 7 covers it. The point here is the shape: a small function handed to another function, where the ceremony of function and return is most of the line.
Where they break: as an object method:
const counter = {
count: 0,
increment: () => {
this.count = this.count + 1; // `this` is NOT the counter object
},
incrementProperly() {
this.count = this.count + 1; // `this` IS the counter object
},
};
counter.incrementProperly();
console.log(counter.count); // 1
counter.increment();
console.log(counter.count); // 1 <- unchanged, the arrow missed
An arrow does not get its own this. It uses whatever this meant in the surrounding code, which for an object literal is not the object. Intermediate covers the mechanism in full.
A practical rule:
// Standalone function that does a job: declaration
function calculateTotal(items) { }
// Short function passed to something else: arrow
items.filter((item) => item.inStock);
// Method on an object: shorthand method syntax
const cart = {
items: [],
add(item) {
this.items.push(item);
},
};
Pro Tip: Choose by role, not by taste. Declarations for named standalone work, arrows for the small throwaway functions you hand to
map,filterand event handlers, and method shorthand for anything attached to an object. Following that split means you will essentially never be bitten bythis, which is the hardest part of the language to reason about.
