Sub topic 14
Choosing the Right Function Form
This chapter brings the earlier chapters together into a set of decision rules. It assumes you already know the material covered so far: declarations and expressions, hoisting and the temporal dead zone, arrow syntax, default and rest parameters, how this is bound, the arguments object, constructors, and class field arrows. Nothing new about the language is introduced here. The aim is to make the choice between forms quick and deliberate.
The Question to Ask First
Most of the time the syntax doesn't matter much. Behavior does. A regular function (declaration or expression) and an arrow function differ in four ways:
| Behavior | Declaration | Function expression | Arrow function |
|---|---|---|---|
| Hoisted with its body | Yes | No (TDZ with `let`/`const`) | No (TDZ with `let`/`const`) |
| Own `this` | Yes, set by the call | Yes, set by the call | No, uses the surrounding `this` |
| Own `arguments` | Yes | Yes | No |
| Callable with `new` | Yes | Yes | No, throws `TypeError` |
| Has `prototype` property | Yes | Yes | No |
| Can be a generator (`function*`) | Yes | Yes | No |
So before picking a form, ask: does this function need its own this, need to be a constructor, or need to be a generator? If any answer is yes, an arrow is ruled out. If every answer is no, the remaining choice comes down to hoisting, naming, and readability.
Object Methods: Use Method Shorthand
When a function lives on an object and reads this, use method shorthand. An arrow as an object property is a common bug, because an object literal does not create a this scope. The arrow takes this from wherever the object literal was written.
const user = {
name: 'Ada',
greet() {
return `Hi, ${this.name}`;
},
greetArrow: () => {
return this === user;
}
};
console.log(user.greet()); // Hi, Ada
console.log(user.greetArrow()); // falseMethod shorthand also keeps super working inside object literals and classes, which neither arrows nor name: function () {} properties support.
Callbacks: Default to Arrows
Callbacks for array methods, promises, and timers usually don't want their own this. Arrows are shorter and avoid the "lost this" problem when the callback runs inside a method.
class Cart {
constructor(items, taxRate) {
this.items = items;
this.taxRate = taxRate;
}
totals() {
return this.items.map(item => item.price * (1 + this.taxRate));
}
}
const cart = new Cart([{ price: 10 }, { price: 20 }], 0.5);
console.log(cart.totals()); // [ 15, 30 ]A regular function callback here would get this as undefined (class bodies run in strict mode) and throw when it reads this.taxRate.
The exception is a callback API that deliberately passes a meaningful this. Some libraries, and DOM addEventListener handlers, set this to the element or to a context object. If your code depends on that value, use a regular function expression. If it doesn't, an arrow is fine, and reading event.currentTarget is clearer than relying on this anyway.
Class Members: Prototype Method or Arrow Field
Inside a class you have two options for a function that uses the instance:
- A prototype method (
handle() {}) is shared by all instances, can be overridden and called throughsuper, and losesthiswhen detached. - An arrow class field (
handle = () => {}) is created per instance, always keepsthis, cannot be called throughsuper, and is not on the prototype.
class Widget {
method() {
return 'method';
}
field = () => 'field';
}
const a = new Widget();
const b = new Widget();
console.log(a.method === b.method); // true
console.log(a.field === b.field); // false
console.log('method' in Widget.prototype); // true
console.log('field' in Widget.prototype); // falseUse a prototype method by default. Use an arrow field only when the function will be passed around detached, as an event handler or callback, and you would otherwise write this.handle = this.handle.bind(this) in the constructor.
Top-Level Helpers: Declaration or const
For named, standalone functions in a module, both styles are common, and teams usually pick one.
Function declarations are hoisted with their bodies. That allows a "main logic first, helpers below" layout:
console.log(formatReport([3, 1, 2])); // Total: 6
function formatReport(values) {
return `Total: ${sum(values)}`;
}
function sum(values) {
return values.reduce((acc, v) => acc + v, 0);
}const with an arrow or function expression enforces define-before-use, through the temporal dead zone, and stops the name from being reassigned. A declaration's binding can be overwritten later by formatReport = ..., while a const binding can't.
| Concern | Prefer declaration | Prefer `const` |
|---|---|---|
| Want top-down reading order | Yes | No |
| Want reassignment to be an error | No | Yes |
| Function uses `this` or `new` | Yes | Only with `function` expression |
| Consistency with arrow-heavy code | No | Yes |
Recursion and Stack Traces
A recursive function needs a name that refers to itself reliably. A declaration gives you that. In an expression, use a named function expression so the inner name can't be broken by reassigning the outer variable:
let countdown = function tick(n) {
return n === 0 ? 'done' : tick(n - 1);
};
const saved = countdown;
countdown = null;
console.log(saved(3)); // doneIf the function had called countdown(n - 1) instead, it would throw after the reassignment.
For stack traces, JavaScript infers names for functions assigned to variables and properties, so const handler = () => {} has handler.name === 'handler'. Inline anonymous callbacks get no name:
const handler = () => {};
console.log(handler.name); // handler
console.log((() => {}).name); // (empty string)
console.log((function work() {}).name); // workWhen a long or error-prone callback shows up in traces as <anonymous>, either pull it out into a named const or give it a name as a function expression.
Constructors and Generators
If you need new, the modern answer is a class. A plain constructor function is still valid, and you'll see it in older code, but never an arrow. Generators have no arrow form at all:
function* range(start, end) {
for (let i = start; i < end; i++) yield i;
}
console.log([...range(0, 4)]); // [ 0, 1, 2, 3 ]Async functions, by contrast, work in every form: async function f() {}, const f = async function () {}, and const f = async () => {}.
Private Scope: IIFE or Module
An IIFE (immediately invoked function expression) creates a private scope that runs once. In code that uses ES modules, each file already has its own scope, and a block { ... } with let/const gives local scope too. Reach for an IIFE when you need a value computed with several statements in an expression position, or when you write classic scripts without modules. An async arrow IIFE is a common way to use await where top-level await isn't available:
(async () => {
const value = await Promise.resolve(42);
console.log(value); // 42
})();Common Mistakes When Choosing
- Using an arrow as an object method or prototype method, then reading
this. Use method shorthand. - Using a regular
functioncallback inside a method and then writingconst self = this. Use an arrow. - Making every class method an arrow field "to be safe". This costs memory and breaks
super. Bind only what you detach. - Relying on hoisting for a
constarrow and hitting aReferenceError. Move the definition up or switch to a declaration. - Writing
argumentsinside an arrow and silently getting the outer function'sarguments(or aReferenceErrorat module top level). Use rest parameters. - Declaring functions inside
ifblocks and relying on them outside. Their behavior differs between strict and sloppy mode, so assign an expression to aletdeclared outside the block instead.
Exercise
A Timer class has a tick() method that increments this.seconds. You pass it as setInterval(this.tick, 1000) inside start(), and this.seconds never changes. Give two fixes and the trade-off between them.
Show answer
Fix 1: pass an arrow, setInterval(() => this.tick(), 1000), or bind it, setInterval(this.tick.bind(this), 1000). tick stays a shared prototype method that subclasses can override. Fix 2: turn tick into an arrow class field, tick = () => { this.seconds++; }. Then setInterval(this.tick, 1000) works anywhere, but every instance gets its own copy and subclasses cannot call super.tick().
Exercise
Choose a form for each and say why: (a) a function passed to array.filter that checks x > 0; (b) a toString on an object literal that returns this.name; (c) a function that yields the Fibonacci sequence; (d) a recursive tree walker assigned to a variable that other code might reassign.
Show answer
(a) An arrow, x => x > 0, because it's short and needs no this. (b) Method shorthand, toString() { return this.name; }, because it needs this to be the object. (c) A generator declaration or expression, function* fib() {}, because arrows cannot be generators. (d) A named function expression, let walk = function walkNode(node) { ... walkNode(child) ... }, so the recursion uses the inner name and survives reassignment of walk.
Exercise
Why does const api = { load: () => this.url, url: '/data' }; api.load() not return '/data', and does api.load.call(api) fix it?
Show answer
The arrow takes this from the scope where the object literal was written, not from api, so this.url is not api.url. call(api) does not fix it, because call, apply, and bind cannot change an arrow's this. Use method shorthand: load() { return this.url; }.