Appearance
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:
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()- Method call: the thing before the dot,
cart, becomesthis. - Plain call after extracting the method: there is no dot, so
thisisundefined. This is the most commonthisbug. callsetsthisexplicitly (question 16).newcreates an object and makes itthisinside the constructor.- Arrow function inside a method: it has no
this, so it usesopen'sthis, which isshop(question 17).
Where the "lost this" bug bites in real code:
- Passing a method as a callback:
button.addEventListener('click', cart.checkout)calls it withoutcart. - 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'call:thisfirst, then the arguments separated by commas.apply:thisfirst, then all arguments in one array. Useful when the arguments already sit in an array.bind: returns a new function whosethisis locked touk.bindwith arguments: also locks the first argument, making a more specific function. This is called partial application.
| Runs now? | Arguments | Returns | |
|---|---|---|---|
call | Yes | Listed: a, b | The result |
apply | Yes | Array: [a, b] | The result |
bind | No | Optional, fixed in advance | A new function |
A memory trick: apply takes an array, call takes commas.
Things to know:
- A bound function cannot be re-bound: calling
.bindor.callon it again does not change itsthis. Onlynewoverrides it. - Since spread syntax exists,
applyis rarely needed:Math.max(...prices)does whatMath.max.apply(null, prices)used to. - Arrow functions ignore all three for
this, because they have nothisof 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 function | Arrow function | |
|---|---|---|
this | Decided by how it is called | Taken from the surrounding code |
arguments object | Yes | No; use rest parameters ...args |
Can be used with new | Yes | No: TypeError |
prototype property | Yes | No |
| Can be a generator | Yes, function* | No |
| Hoisted | Declarations, yes | No, 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)
}
}- The arrow uses
start'sthis, which is theOrderPollerinstance. WithsetInterval(function () { this.attempts += 1 }),thiswould not be the poller: it is the timer object in Node.js andwindowin a browser, soattemptswould 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
}- The arrow takes
thisfrom where the object literal is written, the module scope, sothisisundefinedthere. An object literal does not create athis. - A method shorthand gets
thisfrom 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 functionReturning 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- Returns a new function with the same arguments as the original.
- Calls the original and passes its result through.
finallyalways 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
}- Mutating an argument: the caller's array is now in a different order, which can surprise code elsewhere.
- Writing to a variable outside the function.
- Logging and reading the time: the result of the log differs on every call.
What purity buys you:
| Benefit | Why |
|---|---|
| Predictable | Same input, same output, every time |
| Easy to cache | You can memoise it safely (question 21) |
| Safe to run in any order, or in parallel | No shared state to fight over |
| Easy to reason about | Nothing 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]- A curried function: it takes
rateand returns a function that takesamount. - Supplying the first argument creates a specialised function, which remembers
ratein a closure (question 11). - Supplying the last argument produces the result.
Currying versus partial application:
| Currying | Partial application | |
|---|---|---|
| Shape | Always one argument at a time | Fix some arguments, pass the rest later |
| Example | f(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- A private cache, kept alive by the closure.
- Cache hit: return the stored result at once.
- Cache miss: compute it, store it, return it.
Things that go wrong:
| Problem | Example | Fix |
|---|---|---|
| Impure function | Memoising a price that changes over time | Only memoise pure functions, or add an expiry |
| Object arguments | { id: 1 } is a new key every time | Build a key such as JSON.stringify(args), carefully |
| Unbounded growth | Every postcode in the country cached | Limit the size, such as an LRU cache (question 102) |
| Caching errors or promises | A failed request cached for ever | Delete 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
}- Declaration: hoisted with its body (question 9).
- Expression in a
const: the variable is in its temporal dead zone until its line runs. - 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.
| Declaration | Expression | |
|---|---|---|
| Syntax | function name() {} as a statement | const name = function () {}, () => {} |
| Hoisted | Yes, with the body | No, only the variable, per var, let or const rules |
| Name required | Yes | No |
| Typical use | Top-level helpers | Callbacks, 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.