Arrow Functions & this: Who Am I?

Arrow Functions & this: Who Am I? in TypeScript: Picture the vehicle office of a delivery firm. It runs two kinds of car.

The Analogy: Pool Cars and Allocated Cars at the Fleet Office

Picture the vehicle office of a delivery firm. It runs two kinds of car. A pool car sits in the yard with a blank logbook, and anyone can sign it out for the morning. An allocated car is written into one named employee's logbook the day it is handed over, and it stays theirs. Both cars drive the same roads; the difference is only in how the office decides who answers for each trip.

The pool car settles who answers for it at the moment of each trip. Whoever signs the keys out that morning becomes the driver of record, so the fuel, the tolls, and any parking notice land on their desk. Sign the same car out to a different person tomorrow and every charge now follows that person instead. The car has no memory of who drove it last; the office reads the sign-out sheet for the current trip and bills whoever is on it. A regular function behaves exactly this way: the object it treats as this is chosen fresh at each call, from whoever the caller wrote to the left of the dot.

The allocated car settles the question once, on allocation day, and never revisits it. The logbook names one employee, and that entry is not rewritten when someone borrows the car for an afternoon. Lend it, park it, hand the keys around the yard, and every charge still traces back to the employee it was allocated to, because that was fixed where the car was booked out, not where it happens to be driven. An arrow function is the allocated car: it captures this from the place it was written and carries that binding for life, so no caller can change who it answers to.

The failure shows up when a pool car is sent out on an automated overnight shuttle that nobody signs for. The run happens, the tolls are logged, and the next morning the office opens the logbook to bill the trip and finds no driver of record at all, because the sheet is blank. There is no one to charge, and the paperwork jams. That is precisely what happens when a regular function is handed to a scheduler or an event source that calls it with no receiver: its this is nobody, and the first line that reads this.count throws. An allocated car never hits this wall, because its logbook was filled in long before the trip.


Syntax or Core Structure

An arrow function is written as a parameter list, a fat arrow, and a body. With a single expression body the value is returned automatically; wrap a returned object literal in parentheses so the braces are not read as a statement block.

// src/forms.ts
const add = (a: number, b: number): number => a + b;
const makePoint = (x: number, y: number) => ({ x, y });
const label = (n: number): string => "n=" + n;

console.log(add(2, 3));
const p = makePoint(4, 7);
console.log(p.x + " " + p.y);
console.log(label(9));

Output:

5
4 7
n=9

add has an expression body, so a + b is returned with no return keyword. makePoint returns an object literal, which must be wrapped in parentheses; without them the braces would be read as a block and the function would return undefined. label builds its string by concatenation. The three calls print 5, then 4 7 read from the point's fields, then n=9.


Technical Depth: Where this Comes From, and How to Pin It Down

A regular function reads this from whoever calls it, an arrow captures this from where it was written, an arrow class property keeps that binding even when detached, and a checked this parameter turns the runtime trap into a compile error.

A regular function reads this from the caller

Assign the same regular function to two different objects and call it through each. The value of this is decided by the object to the left of the dot at the call site, not by where the function was defined.

// src/receiver.ts
function whoAmI(this: { side: string }): string {
    return this.side;
}

const desk = { side: "north", where: whoAmI };
const annex = { side: "south", where: whoAmI };

console.log(desk.where());
console.log(annex.where());

Output:

north
south

One function, two receivers, two answers. desk.where() binds this to desk, so it returns "north"; annex.where() binds this to annex, so the identical function returns "south". This is the pool car: the driver of record is read from the current sign-out, which here is the object before the dot. Detach it -- const f = desk.where; f(); -- and there is no object before the dot, so this is nobody and the call throws.

An arrow captures this from where it was written

An arrow used inside a method takes its this from the enclosing method, so it sees the instance without any help. This is why arrows are the natural choice for the callback passed to map or forEach.

// src/lexical.ts
class Depot {
    private code = "D1";
    private vans = [1, 2, 3];

    plates(): string[] {
        return this.vans.map((v) => this.code + "-" + v);
    }
}

const d = new Depot();
console.log(d.plates().join(" "));

Output:

D1-1 D1-2 D1-3

The arrow (v) => this.code + "-" + v was written inside plates, where this is the Depot instance, so it captures that instance and reads this.code as "D1" for every van. The result is ["D1-1", "D1-2", "D1-3"], joined into "D1-1 D1-2 D1-3". Had the callback been a regular function (v) { return this.code ... }, map would have called it with no receiver and the first read of this.code would have crashed.

An arrow property survives detachment

Declaring a class member as an arrow property binds this to the instance once, in the constructor. Pull the member off the object and call it bare and it still works, because its logbook was filled in at construction.

// src/detached.ts
class Tally {
    count = 0;
    bump = (): void => {
        this.count++;
    };
}

const t = new Tally();
const loose = t.bump;   // pulled off the instance
loose();
loose();
console.log(t.count);
console.log(loose === t.bump);

Output:

2
true

bump is an arrow stored as an own property of the instance, bound to t when t was built. loose reads that one stored reference, so calling it twice raises t.count to 2 even though there is no object before the dot. The second line prints true: loose and t.bump are the same single function object, since an arrow property is created once per instance and merely read on each access, not rebuilt. A regular method bump() detached the same way would throw on the first call.

Declaring this as a checked parameter

TypeScript lets you write this as a fake first parameter. It is erased at compile time and exists only so the compiler can reject calls made with the wrong receiver.

// src/thisparam.ts
function greet(this: { name: string }): string {
    return "hi " + this.name;
}

const ada = { name: "ada" };
console.log(greet.call(ada));
// greet();   // refused at compile time

Output:

hi ada

Output (tsc, for the commented line):

error TS2684: The 'this' context of type 'void' is not assignable to method's 'this' of type '{ name: string; }'.

greet.call(ada) supplies ada as the receiver, so this.name is "ada" and the line prints "hi ada". Calling greet() bare would supply no receiver, and with noImplicitThis on (it comes free with strict) TypeScript refuses it with TS2684 rather than letting it crash at runtime. The parameter contributes nothing to the emitted JavaScript; it is purely a promise the compiler enforces.

Arrow and regular functions at a glance

FeatureArrow functionRegular function
this bindinglexical, fixed where writtendynamic, set by the caller
arguments objectabsentpresent
usable with newnoyes
hoistedno, it is a const bindingyes, declarations hoist
call or apply changes thisnoyes
best used forcallbacks and handlersmethods and constructors

The split is not about taste. Reach for an arrow when you want the surrounding this to carry into a callback, and for a regular function or method when you want a fresh receiver, an arguments object, or a constructor.


Real World Example: A Till That Rings Up a Basket

A shop till rings up a basket of items, keeping a running total and a printable line for each item. The line callback runs inside forEach, so the choice between an arrow and a regular function decides whether the callback can see the till at all. Writing it as an arrow lets this stay the till instance, which is the whole reason the total accumulates correctly.

// src/till.ts
interface Sale {
    item: string;
    qty: number;
    price: number;
}

function pad(text: string, width: number): string {
    return text.padEnd(width);
}

class Till {
    private taken = 0;
    private lines: string[] = [];

    ring(sales: readonly Sale[]): void {
        sales.forEach((s) => {
            const line = s.qty * s.price;
            this.taken += line;
            this.lines.push(pad(s.item, 8) + pad(String(s.qty), 6) + pad(String(s.price), 8) + String(line));
        });
    }

    report(): string {
        const head = "lines: " + this.lines.length;
        const cols = pad("ITEM", 8) + pad("QTY", 6) + pad("PRICE", 8) + "LINE";
        return [head, cols, ...this.lines, "taken: " + this.taken].join("\n");
    }
}

const SALES: readonly Sale[] = [
    { item: "apple", qty: 3, price: 60 },
    { item: "bread", qty: 2, price: 145 },
    { item: "milk", qty: 4, price: 80 },
];

const till = new Till();
till.ring(SALES);
console.log(till.report());

Output:

lines: 3
ITEM    QTY   PRICE   LINE
apple   3     60      180
bread   2     145     290
milk    4     80      320
taken: 790

The callback passed to forEach is an arrow, so its this is captured from ring, where this is the till instance. That is what lets this.taken += line and this.lines.push(...) reach the till's own fields on every iteration. forEach calls its callback with no receiver, so a regular function written in its place would see this as undefined and throw on the first this.taken; the arrow sidesteps that because it never consulted forEach for its receiver.

Trace the figures against the sale rows. The apple line is 3 * 60, which is 180; the bread line is 2 * 145, which is 290; the milk line is 4 * 80, which is 320. Each line is added to taken as it is computed, so the total is 180 + 290 + 320, which is 790, printed in the footer. The report joins a head count of 3 lines, the column header, the three padded rows, and the total into one string.

The design has a genuine flaw worth naming. taken and lines are two separate mutable fields updated in lockstep inside the loop, with no way to reset them; call ring a second time and it appends three more rows and keeps adding to the same taken, silently double-counting the basket. Because the total is stored rather than derived, nothing guarantees it still matches the rows it is printed beside. A sturdier design would keep the raw Sale[] and compute both the rows and the total in a single pass at report time, so the two can never disagree. A second, smaller weakness is that price is a bare number of pence with no unit type, so a caller who passes pounds by mistake gets a plausible-looking but wrong total that no compile check would catch.


Common Mistakes

  1. Using an arrow as an object method that needs its own this. Writing { name: "a", greet: () => this.name } captures the surrounding scope's this, not the object, so greet cannot read name. A method that needs the object should be a regular method.
  1. Passing a bare method as a callback. arr.forEach(obj.handle) strips the receiver, so this inside handle is nobody. Pass (x) => obj.handle(x) or a bound reference instead.
  1. Forgetting parentheses around a returned object literal. () => { x: 1 } returns undefined because the braces are read as a block and x: as a label. Wrap it as () => ({ x: 1 }).
  1. Creating a fresh inline arrow for removeEventListener. removeEventListener("click", (e) => this.f(e)) passes a brand-new function that was never added, so the listener is never removed and leaks. Add and remove the same stored reference.
  1. Reaching for .bind(this) on a hot render path. onClick={this.f.bind(this)} allocates a new function on every render. Bind once in the constructor or use an arrow class property.
  1. Writing a generic arrow as <T>(x: T) => x in a .tsx file. The compiler reads <T> as a JSX tag and errors. Add a trailing comma: <T,>(x: T) => x.
  1. Assuming an arrow class property lives on the prototype. It is created per instance, so a thousand instances mean a thousand closures, and a subclass cannot override it with a prototype method. Use a regular method when you want prototype sharing.
  1. Trying new on an arrow, or reading arguments inside one. Arrows have no [[Construct]] and no arguments object; both throw or resolve to the enclosing scope's arguments. Use a regular function when you need either.
  1. Disabling noImplicitThis to silence the error. Turning the flag off hides the very family of this bugs it exists to catch. Fix the receiver instead, with an arrow, a bind, or a declared this parameter.

Best Practices

  • Default to arrows for callbacks and handlers. When you want the surrounding this to carry into a callback passed to map, forEach, setTimeout, or an event listener, an arrow captures it for free.
  • Use regular functions and methods for prototypes and constructors. Prototype methods, constructors, and anything invoked with new need a caller-chosen or fresh receiver, which only a regular function provides.
  • Keep noImplicitThis on. It comes free with strict and converts a whole family of runtime this crashes into compile errors you fix before shipping.
  • Use an arrow class property for a stable handler reference. When the same function must be handed to both addEventListener and removeEventListener, an arrow property gives one fixed reference per instance that both calls share.
  • Annotate this explicitly on helpers meant to be attached. A function f(this: Foo) signature lets the compiler reject calls made with the wrong receiver, documenting the requirement at the same time.
  • Avoid .bind(this) on a render path. Binding allocates a new function each call; bind once in the constructor or reach for an arrow property so the reference is created a single time.
  • Derive state in one pass rather than mutating parallel fields. Computing a total and its rows together from one source array keeps them from drifting, where two fields updated in lockstep can silently disagree.
  • Reserve regular functions for arguments, new, and caller-chosen this. If none of those are needed, an arrow is shorter and safer; if any of them are, only a regular function will do.

Practice Exercises

  1. The broken interval. Write a class with a start() method that calls setInterval with a regular function that does this.ticks++. Watch it fail because this is not the instance, then fix it by making the callback an arrow.
  1. The detached method, three ways. Given class Greeter { name = "ada"; hello() { return this.name; } }, assign const h = g.hello and call h(). Fix the loss of this three ways: an arrow wrapper at the call site, .bind(g), and rewriting hello as an arrow class property.
  1. The this annotation. Write function total(this: { items: number[] }): number that sums this.items, and call it correctly with .call({ items: [1, 2, 3] }). Then call it bare and read the TS2684 error the compiler reports.
  1. The stable reference. Give a class an arrow property handle, read it twice into two variables, and show with === that both reads return the same function object, explaining why that is exactly what addEventListener and removeEventListener need to pair up.