Sub topic 14
Choosing the Right Function Form
This chapter assumes you have worked through the earlier chapters. You should know how hoisting treats declarations and expressions, how this is bound in regular and arrow functions, and why arrows have no arguments object and no constructor behavior. The goal here is to turn those rules into a quick decision you can make while writing code.
Start From What the Function Needs
Every function form gives you some behaviors and leaves others out. To choose one, ask what the function needs:
- Its own
this? Object methods and prototype methods readthisfrom the call site. That means a regular function or method shorthand. - The surrounding
this? Callbacks inside a method usually want the method'sthis. That means an arrow function. - To be called before its line in the file? Only function declarations are hoisted with their body.
- To call itself while stored in a variable? A named function expression gives you a name that cannot be reassigned from outside.
- To be used with
new? Use a class or a regular function. Arrows throw aTypeError.
Decision Guide
Summary Table
| Situation | Recommended form | Reason |
|---|---|---|
| Top-level reusable helper | Function declaration | Hoisted, and named in stack traces |
| Object or prototype method | Method shorthand | Gets `this` from the call site |
| Callback inside a method | Arrow function | Uses the method's `this` |
| Event handler passed by reference | Arrow class field | `this` stays bound to the instance |
| Recursive function stored in a variable | Named function expression | Has a stable internal name |
| Constructor | `class` | Clear syntax, and it throws if you forget `new` |
| One-time private setup | IIFE or block with `let` | Creates its own scope |
| Variable number of arguments | Any form with `...rest` | Gives a real array, and works in arrows |
All the Choices in One Program
// Top-level helper: declaration, hoisted, named in stack traces
function formatPrice(cents) {
return `$${(cents / 100).toFixed(2)}`;
}
const cart = {
items: [1250, 499, 2000],
// Method that needs this: method shorthand
total() {
// Callback that needs the method's this: arrow
return this.items.reduce((sum, cents) => sum + cents, 0);
},
summary() {
return this.items.map(cents => formatPrice(cents)).join(', ');
}
};
class Timer {
ticks = 0;
// Handler that may be detached: arrow class field
tick = () => {
this.ticks += 1;
return this.ticks;
};
}
// Recursion stored in a variable: named function expression
const countDown = function step(n) {
return n <= 0 ? [0] : [n, ...step(n - 1)];
};
console.log(formatPrice(cart.total())); // $37.49
console.log(cart.summary()); // $12.50, $4.99, $20.00
const { tick } = new Timer();
console.log(tick(), tick()); // 1 2
console.log(countDown(3)); // [ 3, 2, 1, 0 ]Common Mistakes
- Arrow functions as object methods.
{ show: () => this.name }does not see the object. The arrow takesthisfrom the scope around the object literal. - Regular functions as callbacks inside methods.
setTimeout(function () { this.count++ })loses the method'sthis. Switch to an arrow. - Arrow class fields everywhere. Each instance gets its own copy of every arrow field, and subclasses cannot call them with
super. Use them only for handlers that get detached. - Relying on hoisting for readability. Hoisting lets you call a declaration early, but a file that calls functions before defining them is harder to follow. Use it on purpose, for example to put the main logic at the top.
Exercise
A Logger class has a method log(msg) that reads this.prefix. You pass logger.log to an array's forEach, and it prints "undefined: hello". Give two fixes and the trade-off between them.
Show answer
Fix one: pass an arrow wrapper, items.forEach(msg => logger.log(msg)), or bind the method with logger.log.bind(logger). Fix two: define log as an arrow class field, log = (msg) => console.log(${this.prefix}: ${msg}). The wrapper keeps log on the prototype, where it is shared and can be overridden with super. The class field always works when detached, but it creates one function per instance, and subclasses cannot reach it through super.
Exercise
Which form would you choose for each case: (a) a sorting comparator passed to array.sort, (b) a function that builds objects with new and shares methods through a prototype, (c) a recursive tree walker assigned to const walk?
Show answer
(a) An arrow function, such as (a, b) => a - b, because it is short and needs no this. (b) A class, or a regular constructor function, because arrows cannot be used with new and have no prototype. (c) A named function expression, const walk = function visit(node) { ... visit(child) ... }, so the recursion uses a name that outside code cannot reassign.