Updated Nov 29, 2026

03 - Functions, Closures, and this

📋 Jump to Takeaways

🎁 The same function call can have a completely different this depending on how you call it, not where you defined it. That's the rule that breaks every Go and Java developer's mental model.

First-class functions are values. Assign them to variables, pass them as arguments, return them from other functions. If you're coming from Go, you already do this with function literals. The difference: three syntaxes for defining functions, a this keyword that changes meaning based on how you call the function, and closures that show up everywhere.

Three Ways to Define Functions

Function declaration:

function add(a: number, b: number): number {
  return a + b;
}
console.log(add(2, 3)); // 5

Function expression:

const add = function (a: number, b: number): number {
  return a + b;
};
console.log(add(2, 3)); // 5

Arrow function:

const add = (a: number, b: number): number => a + b;
console.log(add(2, 3)); // 5

Arrow functions with a single expression get an implicit return. For multi-line bodies, use braces and an explicit return.

const process = (x: number): number => {
  const doubled = x * 2;
  return doubled + 1;
};
console.log(process(5)); // 11

Use arrow functions for callbacks and short functions. Use declarations for top-level named functions. Expressions are rare in modern code.

Hoisting

Hoisting: function declarations are hoisted. You can call them before they appear in the file.

console.log(greet("alice")); // "hello alice"

function greet(name: string): string {
  return `hello ${name}`;
}

Function expressions and arrow functions are not hoisted. They follow normal variable rules.

// console.log(greet("alice")); // ReferenceError: Cannot access 'greet' before initialization

const greet = (name: string): string => `hello ${name}`;
console.log(greet("alice")); // "hello alice"

In Go, declaration order doesn't matter within a package. Here, it matters for expressions but not for declarations. Declare functions before you use them and you'll never hit this.

The this Keyword

The this keyword is the single biggest WTF for developers coming from Go, Python, or Java. In those languages, this (or self) always refers to the instance. Here, this depends on how the function is called, not where it's defined.

const user = {
  name: "alice",
  greet() {
    console.log(`hi, i'm ${this.name}`);
  },
};

user.greet(); // "hi, i'm alice" (this = user)

const greetFn = user.greet;
greetFn(); // TypeError: Cannot read properties of undefined (reading 'name')
// In strict mode (all TS modules), `this` is undefined — accessing .name throws

user.greet() sets this to user because the function is called as a method on user. Extract the function and call it standalone, this is undefined in strict mode — and accessing a property on undefined throws.

This bites you constantly with callbacks:

class Timer {
  seconds = 0;

  start() {
    setInterval(function () {
      this.seconds++; // BUG: 'this' is not the Timer instance
      console.log(this.seconds);
    }, 1000);
  }
}

The function keyword creates its own this binding. Inside setInterval, this is the global object (or undefined in strict mode), not the Timer instance.

Arrow Functions Fix this

Arrow functions don't have their own this. They capture this from the surrounding scope (lexical binding). This is almost always what you want.

class Timer {
  seconds = 0;

  start() {
    setInterval(() => {
      this.seconds++; // Works: arrow function captures 'this' from start()
      console.log(this.seconds);
    }, 1000);
  }
}

const t = new Timer();
t.start();
// 1
// 2
// 3
// ...

This is why arrow functions dominate modern TypeScript. They kill an entire class of bugs.

// Regular function: this depends on call site
const obj = {
  value: 10,
  getRegular: function () {
    return this.value;
  },
  getArrow: () => {
    return this; // captures 'this' from module scope, NOT obj
  },
};

console.log(obj.getRegular()); // 10
console.log(obj.getArrow());   // undefined (module-scope this is undefined in strict mode)

Gotcha: don't use arrow functions as object methods. They capture this from the enclosing scope, which is the module, not the object.

Closures

A closure is a function that remembers variables from its outer scope, even after that scope has finished executing. If you've used function literals in Go, you've used closures.

function makeCounter(): () => number {
  let count = 0;
  return () => {
    count++;
    return count;
  };
}

const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3

count lives on even though makeCounter has returned. The inner function holds a reference to it.

Factory functions use closures to create private state:

function createLogger(prefix: string) {
  return {
    info: (msg: string) => console.log(`[${prefix}] INFO: ${msg}`),
    error: (msg: string) => console.log(`[${prefix}] ERROR: ${msg}`),
  };
}

const db = createLogger("DB");
db.info("connected");   // [DB] INFO: connected
db.error("timeout");    // [DB] ERROR: timeout

No classes needed. The prefix variable is captured by the returned functions and can't be accessed from outside. This pattern is everywhere in Node.js libraries.

Higher-Order Functions

Functions that take functions as arguments or return functions. In Go, you'd write a for loop. In TypeScript, you use map, filter, and reduce.

const numbers = [1, 2, 3, 4, 5];

// map: transform each element
const doubled = numbers.map((n) => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

// filter: keep elements that pass a test
const evens = numbers.filter((n) => n % 2 === 0);
console.log(evens); // [2, 4]

// reduce: accumulate into a single value
const sum = numbers.reduce((acc, n) => acc + n, 0);
console.log(sum); // 15

Go equivalent of map:

// Go: you write the loop yourself
doubled := make([]int, len(numbers))
for i, n := range numbers {
    doubled[i] = n * 2
}

These methods chain:

const result = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  .filter((n) => n % 2 === 0)
  .map((n) => n * 3)
  .reduce((acc, n) => acc + n, 0);

console.log(result); // 90

find returns the first match. some checks if any element passes. every checks if all pass.

const users = [
  { name: "alice", active: true },
  { name: "bob", active: false },
  { name: "charlie", active: true },
];

const found = users.find((u) => u.name === "bob");
console.log(found); // { name: "bob", active: false }

console.log(users.some((u) => u.active));  // true
console.log(users.every((u) => u.active)); // false

Rest Parameters and Spread

Rest parameters collect remaining arguments into an array. Like Go's variadic ... but the syntax is on the parameter, not the type.

function sum(...nums: number[]): number {
  return nums.reduce((acc, n) => acc + n, 0);
}

console.log(sum(1, 2, 3));    // 6
console.log(sum(10, 20));     // 30

Spread expands an array into individual arguments:

const parts = [1, 2, 3] as const;
console.log(Math.max(...parts)); // 3

// Combine arrays
const a = [1, 2];
const b = [3, 4];
const combined = [...a, ...b];
console.log(combined); // [1, 2, 3, 4]

Same idea as Go's nums... for spreading a slice into a variadic function. Different syntax.

bind

bind returns a new function with this permanently set to a value you choose. You'll see it in older Node.js code and whenever a method gets passed as a callback and would otherwise lose its this context.

class Timer {
  private label: string;
  constructor(label: string) { this.label = label; }

  tick() {
    console.log(`${this.label}: tick`);
  }
}

const t = new Timer("server");
const fn = t.tick.bind(t);  // this is permanently t
setTimeout(fn, 100);        // "server: tick" — works without arrow wrapper

In modern code, an arrow function in the class body (tick = () => { ... }) does the same thing with less ceremony. Use bind when you encounter it in existing code, or when working with APIs that hand you a bare function reference.

Key Takeaways

  • Three function syntaxes: declarations (hoisted), expressions, arrows (lexical this)
  • this in regular functions depends on the call site, not the definition. This is the #1 source of bugs for backend devs.
  • Arrow functions capture this from the enclosing scope. Use them for callbacks, always.
  • Closures let inner functions access outer variables after the outer function returns. Used for factories and private state.
  • map, filter, reduce replace explicit loops. They chain for readable data transformations.
  • Rest (...args) collects arguments. Spread (...array) expands them. Same ... syntax, opposite directions.

🎁 Go structs have a fixed shape at compile time. JavaScript objects can gain and lose properties at runtime — and every object has a hidden prototype chain that can inject properties you never defined. What could go wrong?

📝 Ready to test your knowledge?

Answer the quiz below to mark this lesson complete.

Spot something off? Report an issue