Skip to content

Interview PrepBasics · Core

this and Functions ​

15. How does the this keyword work in different calling contexts? ​

The short answer

For a regular function, this is decided by how the function is called, not where it is written. Called as order.total(), this is order. Called as a plain total(), it is undefined in strict mode. With call, apply or bind, it is whatever you pass. With new, it is the new object being built. Arrow functions are the exception: they have no this of their own and use the this of the code around them.

The rules, checked in this order:

① arrow function?this of the surrounding code② called with new?the new object being built③ call, apply or bind?the value you passed in④ called as obj.method()?obj, the thing before the dot⑤ plain call: fn()undefined in strict mode, global otherwiseyesyesyesyes
Ask five questions, in order. The first "yes" decides this. If every answer is "no", it is a plain call.

Each rule in code, with a shopping cart:

js
'use strict'

const cart = {
  owner: 'Priya',
  greet() { return `Hi ${this.owner}` },             // regular method
}

cart.greet()                          // (1) 'Hi Priya'

const greet = cart.greet
greet()                               // (2) TypeError: Cannot read properties of undefined

greet.call({ owner: 'Ravi' })         // (3) 'Hi Ravi'

function Cart(owner) { this.owner = owner }
const c = new Cart('Ana')            // (4) c.owner === 'Ana'

const shop = {
  name: 'Corner Shop',
  open() {
    setTimeout(() => console.log(this.name), 10)     // (5) 'Corner Shop'
  },
}
shop.open()
  1. Method call: the thing before the dot, cart, becomes this.
  2. Plain call after extracting the method: there is no dot, so this is undefined. This is the most common this bug.
  3. call sets this explicitly (question 16).
  4. new creates an object and makes it this inside the constructor.
  5. Arrow function inside a method: it has no this, so it uses open's this, which is shop (question 17).

Where the "lost this" bug bites in real code:

  • Passing a method as a callback: button.addEventListener('click', cart.checkout) calls it without cart.
  • Passing a class method to a timer or a promise: setTimeout(this.save, 100).

The fixes: wrap it in an arrow function, () => cart.checkout(), or bind it once, cart.checkout.bind(cart), or define the method as an arrow function class field (see the class questions).

Event handlers in the browser are a special case: with a regular function, this is the element the listener is attached to.

16. What is the difference between call, apply, and bind? ​

The short answer

All three set what this will be inside a function. call runs the function immediately, with arguments listed one by one. apply also runs it immediately, but takes the arguments as one array. bind does not run the function: it returns a new function with this, and optionally some arguments, fixed for ever, which you can call later.

ts
function formatTotal(this: { currency: string }, amount: number, tax: number) {
  return `${(amount + tax).toFixed(2)} ${this.currency}`
}

const uk = { currency: 'GBP' }

formatTotal.call(uk, 100, 20)             // (1) '120.00 GBP'
formatTotal.apply(uk, [100, 20])          // (2) '120.00 GBP'

const formatUk = formatTotal.bind(uk)     // (3) nothing runs yet
formatUk(50, 10)                          // '60.00 GBP'

const withStdTax = formatTotal.bind(uk, 100)   // (4) partial application
withStdTax(20)                            // '120.00 GBP'
  1. call: this first, then the arguments separated by commas.
  2. apply: this first, then all arguments in one array. Useful when the arguments already sit in an array.
  3. bind: returns a new function whose this is locked to uk.
  4. bind with arguments: also locks the first argument, making a more specific function. This is called partial application.
Runs now?ArgumentsReturns
callYesListed: a, bThe result
applyYesArray: [a, b]The result
bindNoOptional, fixed in advanceA new function

A memory trick: apply takes an array, call takes commas.

Things to know:

  • A bound function cannot be re-bound: calling .bind or .call on it again does not change its this. Only new overrides it.
  • Since spread syntax exists, apply is rarely needed: Math.max(...prices) does what Math.max.apply(null, prices) used to.
  • Arrow functions ignore all three for this, because they have no this of their own.

Writing your own bind is a classic task (question 103).

17. How do arrow functions differ from regular functions? ​

The short answer

Arrow functions are a shorter syntax, but they also behave differently. They have no this of their own and use the this of the code around them, which call, apply and bind cannot change. They have no arguments object, cannot be used with new, have no prototype, and cannot be generators. Use them for callbacks and short functions; use regular functions or methods when you need your own this, such as object methods.

Regular functionArrow function
thisDecided by how it is calledTaken from the surrounding code
arguments objectYesNo; use rest parameters ...args
Can be used with newYesNo: TypeError
prototype propertyYesNo
Can be a generatorYes, function*No
HoistedDeclarations, yesNo, they are expressions in a variable

Where arrows shine: callbacks inside methods.

ts
class OrderPoller {
  private attempts = 0

  start() {
    setInterval(() => {
      this.attempts += 1                     // (1) this is the poller
      console.log('poll', this.attempts)
    }, 1000)
  }
}
  1. The arrow uses start's this, which is the OrderPoller instance. With setInterval(function () { this.attempts += 1 }), this would not be the poller: it is the timer object in Node.js and window in a browser, so attempts would never change on the poller.

Where arrows are wrong: object methods that need this.

ts
const basket = {
  items: ['tea', 'milk'],
  count: () => this.items.length,           // (1) wrong
  countRight() { return this.items.length }, // (2) right
}
  1. The arrow takes this from where the object literal is written, the module scope, so this is undefined there. An object literal does not create a this.
  2. A method shorthand gets this from the call, basket.countRight().

Arrow class fields solve the "lost this" callback bug in classes:

ts
class CheckoutButton {
  label = 'Pay'
  handleClick = () => console.log(this.label)   // always bound to the instance
}

The trade-off: each instance gets its own copy of the function instead of sharing one on the prototype, which costs a little memory.

18. What are higher-order functions? ​

The short answer

A higher-order function is a function that takes another function as an argument, returns a function, or both. JavaScript allows this because functions are values, like numbers or strings. Familiar examples are map, filter, reduce, setTimeout, addEventListener and Express middleware. They let you separate what to do from how to repeat it, and build reusable helpers such as retry, logging or caching wrappers.

Taking a function:

ts
const prices = [12, 40, 7, 25]
const withVat = prices.map((p) => p * 1.2)        // map takes a function
const expensive = prices.filter((p) => p > 20)    // filter takes a function

Returning a function, a reusable timing wrapper:

ts
function timed<A extends unknown[], R>(name: string, fn: (...args: A) => Promise<R>) {
  return async (...args: A): Promise<R> => {          // (1)
    const start = performance.now()
    try {
      return await fn(...args)                        // (2)
    } finally {
      console.log(`${name} took ${Math.round(performance.now() - start)} ms`)  // (3)
    }
  }
}

const loadCart = timed('loadCart', async (userId: string) => fetchCart(userId))
await loadCart('u-17')     // prints: loadCart took 84 ms
  1. Returns a new function with the same arguments as the original.
  2. Calls the original and passes its result through.
  3. finally always logs, whether the call succeeded or threw.

Why it matters: the same timed wrapper works for any async function. Behaviour such as timing, retrying, caching and permission checks is written once and wrapped around many functions, instead of being copied into each of them. Decorators in TypeScript and middleware in Express are the same idea.

19. What are pure functions and side effects? ​

The short answer

A pure function always returns the same output for the same input, and does nothing else: it changes no outside state and performs no input or output. A side effect is anything a function does besides returning a value, such as writing to a database, changing a global or an argument, logging, or reading the clock. Pure functions are easy to reason about, reuse and cache. Real programs need side effects, so the goal is to keep them few and at the edges.

ts
// Pure: depends only on its inputs, changes nothing
function cartTotal(items: { price: number; qty: number }[]) {
  return items.reduce((sum, i) => sum + i.price * i.qty, 0)
}

// Impure: three side effects
let lastTotal = 0
function cartTotalAndSave(items: { price: number; qty: number }[]) {
  items.sort((a, b) => a.price - b.price)         // (1) changes the caller's array
  const total = cartTotal(items)
  lastTotal = total                               // (2) changes outside state
  console.log('total', total, new Date())         // (3) output and the clock
  return total
}
  1. Mutating an argument: the caller's array is now in a different order, which can surprise code elsewhere.
  2. Writing to a variable outside the function.
  3. Logging and reading the time: the result of the log differs on every call.

What purity buys you:

BenefitWhy
PredictableSame input, same output, every time
Easy to cacheYou can memoise it safely (question 21)
Safe to run in any order, or in parallelNo shared state to fight over
Easy to reason aboutNothing hidden happens

The practical pattern: a pure core and a thin shell. Keep the business logic, such as price calculation, discount rules or validation, pure. Put database calls, HTTP calls and logging in a thin layer around it. Then the important logic is simple to read and change.

Avoid mutating arguments by accident. Methods such as sort, reverse and splice change the array in place. Their newer copies, toSorted, toReversed and toSpliced, return a new array and leave the original alone.

20. What is currying? ​

The short answer

Currying turns a function that takes several arguments into a chain of functions that each take one argument: price(tax)(amount) instead of price(tax, amount). Each call returns a new function that remembers the arguments so far, through a closure, until all are supplied. It is useful for building specialised functions from general ones, such as a withUkTax function made from a general tax function.

ts
const applyTax = (rate: number) => (amount: number) => amount * (1 + rate)   // (1)

const withUkVat = applyTax(0.2)          // (2)
const withNoTax = applyTax(0)

console.log(withUkVat(100))              // (3) 120
console.log([10, 20].map(withUkVat))     // [12, 24]
  1. A curried function: it takes rate and returns a function that takes amount.
  2. Supplying the first argument creates a specialised function, which remembers rate in a closure (question 11).
  3. Supplying the last argument produces the result.

Currying versus partial application:

CurryingPartial application
ShapeAlways one argument at a timeFix some arguments, pass the rest later
Examplef(a)(b)(c)f.bind(null, a) then g(b, c)

Where you meet it: configuration of middleware, withRole('admin')(handler); selectors and helpers in functional libraries; and the "write a curry function" interview task (question 95).

When not to use it: for ordinary business code with two or three arguments, a normal function with named parameters, or an options object, is clearer to most readers.

21. What is memoization? ​

The short answer

Memoisation is caching a function's results by its arguments, so a repeated call with the same arguments returns the stored result instead of computing it again. It works safely only for pure functions, whose result depends only on their inputs. It trades memory for speed, so a real memoisation cache needs a limit or an expiry, or it can grow without end.

ts
function memoize<A extends string | number, R>(fn: (arg: A) => R) {
  const cache = new Map<A, R>()                    // (1)
  return (arg: A): R => {
    if (cache.has(arg)) return cache.get(arg)!     // (2)
    const result = fn(arg)                         // (3)
    cache.set(arg, result)
    return result
  }
}

const shippingCost = memoize((postcode: string) => {
  // imagine an expensive lookup in a big rate table
  return postcode.startsWith('E') ? 3.5 : 5
})

shippingCost('E1 6AN')   // computed
shippingCost('E1 6AN')   // returned from the cache
  1. A private cache, kept alive by the closure.
  2. Cache hit: return the stored result at once.
  3. Cache miss: compute it, store it, return it.

Things that go wrong:

ProblemExampleFix
Impure functionMemoising a price that changes over timeOnly memoise pure functions, or add an expiry
Object arguments{ id: 1 } is a new key every timeBuild a key such as JSON.stringify(args), carefully
Unbounded growthEvery postcode in the country cachedLimit the size, such as an LRU cache (question 102)
Caching errors or promisesA failed request cached for everDelete the entry when it fails

Memoising async calls. Store the promise, not the result, so ten callers asking at the same moment share one request. Remove the entry if the promise rejects, or every later caller gets the same error.

In React, useMemo and React.memo are memoisation of rendering work, covered in the React module.

22. What is the difference between function declarations and function expressions? ​

The short answer

A function declaration is a statement that starts with the function keyword, such as function total() {}; it is hoisted with its body, so it can be called before the line where it is written. A function expression creates a function as part of an expression, usually assigned to a variable, such as const total = function () {} or an arrow function; it only exists once that line has run. Named function expressions also give clearer stack traces.

ts
console.log(subtotal([5, 10]))          // (1) 15: works before the definition

function subtotal(prices: number[]) {
  return prices.reduce((a, b) => a + b, 0)
}

console.log(total([5, 10]))             // (2) ReferenceError

const total = function total(prices: number[]) {   // (3)
  return subtotal(prices) * 1.2
}
  1. Declaration: hoisted with its body (question 9).
  2. Expression in a const: the variable is in its temporal dead zone until its line runs.
  3. A named function expression: the inner name appears in stack traces and can be used inside the function for recursion, but it is not added to the outer scope.
DeclarationExpression
Syntaxfunction name() {} as a statementconst name = function () {}, () => {}
HoistedYes, with the bodyNo, only the variable, per var, let or const rules
Name requiredYesNo
Typical useTop-level helpersCallbacks, values passed around, conditional definitions

Which to use is mostly style. Many teams use declarations for named top-level helpers, because they read well and can be ordered from high level to low level, and arrow functions for callbacks and short functions.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
JavaScript & TypeScript
Basics
Async
TypeScript
Write it yourself
Other topics
Nothing picked yet