Skip to content

Interview PrepBasics · Basics

Arrays, Iteration and Copying ​

41. What is the difference between map(), filter(), reduce(), and forEach()? ​

The short answer

All four walk through an array and call your function for each item, but they return different things. map returns a new array of the same length, with each item transformed. filter returns a new array with only the items for which your function returns true. reduce combines all items into one value, such as a total. forEach returns nothing and is only for side effects, such as logging. None of them change the original array.

One cart, four methods:

ts
const cart = [
  { sku: 'tea', price: 3.5, qty: 2 },
  { sku: 'mug', price: 8, qty: 1 },
  { sku: 'jam', price: 2.25, qty: 0 },
]

const lineTotals = cart.map((i) => i.price * i.qty)            // (1) [7, 8, 0]
const inBasket = cart.filter((i) => i.qty > 0)                 // (2) tea and mug
const total = cart.reduce((sum, i) => sum + i.price * i.qty, 0) // (3) 15
cart.forEach((i) => console.log(i.sku))                        // (4) prints, returns undefined
  1. map: one output for every input, so 3 in, 3 out.
  2. filter: keeps only the items where the function returns true.
  3. reduce: sum starts at 0, the second argument. Each step returns the new running total, which becomes sum for the next item.
  4. forEach: just runs the function. Its return value is always undefined.
sum = 0tea: 3.5 × 2mug: 8 × 1jam: 2.25 × 0sum = 7sum = 15sum = 15result 15
reduce carries one value along. The running total starts at 0. Each item adds its line total and passes the new sum to the next step. The last sum is the result.
MethodReturnsUse it to
mapNew array, same lengthTransform each item
filterNew array, same or shorterKeep only some items
reduceAny single valueTotal, group, count, build an object
forEachundefinedRun a side effect for each item

Things interviewers like to hear:

  • Chaining reads well: cart.filter((i) => i.qty > 0).map((i) => i.sku). Each step makes a new array, which is fine for normal sizes.
  • Always pass the initial value to reduce. Without it, reduce uses the first item as the start, and an empty array throws TypeError: Reduce of empty array with no initial value.
  • forEach cannot be stopped with break and does not wait for await inside it (question 57). Use a for...of loop when you need either.
  • find, some and every stop early: find returns the first match, some is true if any match, every is true if all match.

42. What are optional chaining and nullish coalescing? ​

The short answer

Optional chaining, ?., reads a property or calls a method only if the value before it is not null or undefined; otherwise the whole expression stops and gives undefined instead of throwing. Nullish coalescing, ??, gives a fallback value only when the left side is null or undefined, unlike ||, which also replaces 0, '' and false. Together they make "read this deep value, or use a default" short and safe.

ts
type Order = { customer?: { address?: { postcode?: string } }; giftWrap?: () => void; qty?: number }

function shipTo(order: Order) {
  const postcode = order.customer?.address?.postcode ?? 'unknown'   // (1)
  order.giftWrap?.()                                                // (2)
  const qty = order.qty ?? 1                                        // (3)
  return { postcode, qty }
}

shipTo({})                   // { postcode: 'unknown', qty: 1 }
shipTo({ qty: 0 })           // { postcode: 'unknown', qty: 0 }
  1. Reads a deep value safely. If customer or address is missing, the chain stops and gives undefined, and ?? replaces it with 'unknown'.
  2. Calls a method only if it exists. Optional chaining also works for calls, fn?.(), and indexes, items?.[0].
  3. ?? keeps 0. With order.qty || 1, a real quantity of 0 would wrongly become 1 (question 35).

| Left side | x || 'default' | x ?? 'default' | |---|---|---| | undefined | 'default' | 'default' | | null | 'default' | 'default' | | 0 | 'default' | 0 | | '' | 'default' | '' | | false | 'default' | false |

Assignment versions: settings.theme ??= 'light' assigns only if the value is nullish. ||= and &&= work the same way for falsy and truthy values.

Do not overuse ?.. If a value must always exist, such as a logged-in user on an authenticated route, user?.id hides a real bug by silently producing undefined. Let it throw, or check it once at the top and fail clearly.

43. What is destructuring, and how does it work? ​

The short answer

Destructuring is syntax for pulling values out of an object or array into separate variables in one step. Object destructuring matches by property name, const { id, total } = order, and array destructuring matches by position, const [first, second] = items. You can rename, set defaults, collect the rest, and go into nested values. It is widely used for function parameters, React props and hook results.

ts
const order = { id: 'A12', total: 40, customer: { name: 'Priya' }, status: undefined }

const { id, total: amount, status = 'new', customer: { name } } = order   // (1)
// id = 'A12', amount = 40, status = 'new', name = 'Priya'

const [first, , third = 'none', ...others] = ['tea', 'mug', 'jam', 'pan', 'cup']  // (2)
// first = 'tea', third = 'jam', others = ['pan', 'cup']

function placeOrder({ sku, qty = 1 }: { sku: string; qty?: number }) {   // (3)
  return `${qty} × ${sku}`
}
placeOrder({ sku: 'tea' })        // '1 × tea'

let a = 1, b = 2;
[a, b] = [b, a]                   // (4) swap: a = 2, b = 1
  1. Object destructuring: total: amount renames, status = 'new' sets a default used only when the value is undefined, and customer: { name } reaches into a nested object.
  2. Array destructuring: by position. A blank skips an item, and ...others collects the rest.
  3. In parameters, it gives named arguments with defaults, so the call reads clearly.
  4. Swapping two variables without a temporary one.

Traps:

  • Destructuring null or undefined throws: const { id } = undefined gives TypeError. Use a default: function f({ id } = {}).
  • Defaults apply only for undefined, not for null.
  • Destructuring copies values, not links, for primitives. For objects, the variable still points to the same nested object (question 45).

44. What are the spread and rest operators? ​

The short answer

Both are written ..., but they do opposite jobs. Spread expands an array or object into its individual parts, for example to copy, merge or pass items as separate arguments: [...a, ...b], { ...defaults, ...options }, Math.max(...prices). Rest collects several remaining parts into one array or object: function log(...messages) or const { password, ...safe } = user. Spread makes shallow copies only.

Spread: expand.

ts
const defaults = { currency: 'GBP', giftWrap: false }
const options = { giftWrap: true }

const settings = { ...defaults, ...options }        // (1) { currency: 'GBP', giftWrap: true }
const allSkus = [...['tea', 'mug'], 'jam']           // (2) ['tea', 'mug', 'jam']
const highest = Math.max(...[12, 40, 7])             // (3) 40
  1. Merging objects: later keys win, so options overrides defaults.
  2. Combining arrays into a new array.
  3. Passing array items as separate arguments.

Rest: collect.

ts
function logEvent(name: string, ...details: unknown[]) {    // (1)
  console.log(name, details.length, 'details')
}
logEvent('checkout', 'A12', 40, 'GBP')    // checkout 3 details

const user = { id: 'u1', email: 'p@shop.example', passwordHash: 'x9…' }
const { passwordHash, ...publicUser } = user                // (2)
// publicUser = { id: 'u1', email: 'p@shop.example' }
  1. Rest parameter: every argument after name lands in one array. It must be last.
  2. Rest in destructuring: takes one field out and keeps the rest. A neat way to drop sensitive fields before sending a user to a client.

The shallow copy trap:

ts
const original = { id: 'A12', items: ['tea'] }
const copy = { ...original }
copy.items.push('mug')
console.log(original.items)     // ['tea', 'mug']: the inner array is shared

Spread copies only the top level. Nested objects and arrays are still shared (question 45).

45. What is the difference between shallow copy and deep copy? ​

The short answer

A shallow copy creates a new top-level object or array, but its nested objects are still the same objects as in the original, so changing a nested value through the copy changes the original too. A deep copy recreates every level, so the copy and the original share nothing. Spread, Object.assign and slice make shallow copies. structuredClone makes deep copies in modern browsers and Node.js.

shallow copyoriginalcopyitems arrayshareddeep copyoriginalcopyitems arrayits own items
Two boxes, one or two insides. A shallow copy is a new outer object pointing at the same inner things. A deep copy rebuilds the inner things too, so the two can change independently.
ts
const order = { id: 'A12', items: [{ sku: 'tea', qty: 1 }], placedAt: new Date() }

const shallow = { ...order }                         // (1)
shallow.items[0].qty = 5
console.log(order.items[0].qty)                      // 5: original changed

const deep = structuredClone(order)                  // (2)
deep.items[0].qty = 9
console.log(order.items[0].qty)                      // 5: original untouched
console.log(deep.placedAt instanceof Date)           // true: dates survive
  1. Shallow: a new outer object, but items is the same array.
  2. Deep: structuredClone copies every level, keeps dates, maps, sets and even circular references.

The ways to copy, compared:

MethodDepthKeeps dates, mapsHandles cyclesCopies functions
{ ...obj }, Object.assignShallowReferences onlyn/aReferences
JSON.parse(JSON.stringify(obj))DeepNo: dates become stringsNo: throwsNo: dropped (question 49)
structuredClone(obj)DeepYesYesNo: throws
A library, such as lodash cloneDeepDeepYesYesReferences

Do you even need a deep copy? Often not. In React and Redux, the usual pattern is to copy only the path you change: { ...order, items: order.items.map(...) }. Unchanged parts are shared, which is cheaper and lets change detection compare references. Writing your own deep clone is a classic task (question 96).

46. What is an iterator, and how does a generator work? ​

The short answer

An iterator is an object with a next() method that returns { value, done } each time it is called, one item at a time. An object is iterable if it has a [Symbol.iterator] method that returns an iterator, which is what lets for...of, spread and destructuring work on it. A generator, written function*, is the easy way to build iterators: each yield hands out one value and pauses the function, and the next next() call resumes it right where it stopped.

A generator for paging through an API, fetching one page at a time:

ts
async function* allOrders(api: (page: number) => Promise<{ items: string[]; hasMore: boolean }>) {
  let page = 1
  while (true) {
    const res = await api(page)              // (1)
    yield* res.items                         // (2)
    if (!res.hasMore) return                 // (3)
    page += 1
  }
}

for await (const orderId of allOrders(fetchOrderPage)) {     // (4)
  console.log(orderId)
  if (orderId === 'A99') break                              // (5)
}
  1. Fetches one page only when the consumer asks for more.
  2. yield* hands out each item of the page one by one, pausing after each.
  3. return ends the generator: the next next() gives done: true.
  4. for await...of pulls items from an async generator.
  5. Stopping early means later pages are never fetched. The work is lazy.

A sync generator, step by step:

ts
function* orderStatuses() {
  yield 'placed'
  yield 'paid'
  yield 'shipped'
}

const it = orderStatuses()
it.next()   // { value: 'placed', done: false }
it.next()   // { value: 'paid', done: false }
it.next()   // { value: 'shipped', done: false }
it.next()   // { value: undefined, done: true }
[...orderStatuses()]   // ['placed', 'paid', 'shipped']

Why generators are useful:

UseWhy
Lazy sequencesValues are produced only when asked for, even endless ones
Paging through APIs or big filesMemory stays small: one page at a time
Custom iteration for your own classesImplement [Symbol.iterator] with function*
Pausable logicThe function keeps its local variables between next() calls

How the pause works. When a generator yields, its execution context, with all its local variables, is saved instead of being thrown away. Calling next() puts it back on the call stack and continues after the yield. Before async/await existed, libraries used exactly this to write asynchronous code that looked synchronous.

47. What is the difference between for...in and for...of? ​

The short answer

for...in loops over the keys, the property names, of an object, including inherited enumerable ones, always as strings. for...of loops over the values of an iterable, such as an array, a string, a Map or a Set. Use for...of for arrays and other collections, and Object.keys or Object.entries with for...of for plain objects. Avoid for...in on arrays.

ts
const skus = ['tea', 'mug']

for (const i in skus) console.log(i, typeof i)   // '0' string, '1' string: keys
for (const s of skus) console.log(s)             // 'tea', 'mug': values

const stock = { tea: 12, mug: 3 }
for (const [sku, qty] of Object.entries(stock)) {
  console.log(sku, qty)                          // tea 12, mug 3
}
for...infor...of
GivesKeys, as stringsValues
Works onAny objectIterables: arrays, strings, Map, Set, generators
Inherited propertiesIncluded, if enumerableNot applicable
Plain objectsYesNo: use Object.entries

Why not for...in on arrays: the index comes as a string, so i + 1 gives '01', and any property added to the array, or to Array.prototype by a library, shows up in the loop.

48. How do you remove duplicates from an array? ​

The short answer

For primitive values, put them in a Set, which keeps only unique values, and spread it back into an array: [...new Set(items)]. It keeps the order of first appearance and runs in linear time. For objects, decide what makes two objects "the same", such as the same id, and keep the first object seen for each key, usually with a Map.

Primitives:

ts
const skus = ['tea', 'mug', 'tea', 'jam', 'mug']
const unique = [...new Set(skus)]          // ['tea', 'mug', 'jam']

Objects, by a key:

ts
type Item = { id: string; name: string }

function uniqueBy<T>(list: T[], key: (item: T) => string): T[] {
  const seen = new Map<string, T>()
  for (const item of list) {
    const k = key(item)
    if (!seen.has(k)) seen.set(k, item)    // keep the first one
  }
  return [...seen.values()]
}

uniqueBy([{ id: '1', name: 'Tea' }, { id: '1', name: 'Tea (dup)' }], (i) => i.id)
// [{ id: '1', name: 'Tea' }]

Why new Set does not work for objects: a Set compares objects by reference. Two separate objects with the same contents are different values (question 32).

Complexity matters in interviews. items.filter((x, i) => items.indexOf(x) === i) also works, but indexOf scans the array for every item, which is O(n²): fine for 100 items, slow for 100,000. The Set and Map versions are O(n).

49. What can go wrong with JSON.stringify and JSON.parse? ​

The short answer

JSON.stringify silently drops functions, undefined values and symbol keys, turns NaN and Infinity into null, turns dates into strings, throws on circular references and on BigInt values, and loses the difference between a Map and an empty object. JSON.parse throws on invalid input, gives back plain objects with no classes or dates, and returns whatever the input contains, so data from outside must be validated after parsing.

ts
const order = {
  id: 'A12',
  placedAt: new Date('2026-10-27T10:00:00Z'),
  discount: undefined,
  total: NaN,
  notify() {},
  tags: new Set(['gift']),
}

JSON.stringify(order)
// '{"id":"A12","placedAt":"2026-10-27T10:00:00.000Z","total":null,"tags":{}}'
ValueAfter JSON.stringify
DateISO string
undefined, functions, symbols in objectsDropped
undefined in arraysnull
NaN, Infinitynull
Map, Set{}
BigIntThrows TypeError
Circular referenceThrows TypeError

Coming back, dates do not return:

ts
const back = JSON.parse(JSON.stringify(order))
typeof back.placedAt          // 'string', not a Date

Safe parsing of outside data:

ts
function parseOrder(text: string) {
  let raw: unknown
  try {
    raw = JSON.parse(text)                       // (1)
  } catch {
    throw new Error('Body is not valid JSON')
  }
  return OrderSchema.parse(raw)                  // (2)
}
  1. JSON.parse throws on malformed input, such as a trailing comma, so wrap it.
  2. Validate the shape, for example with a Zod schema, because parsing only proves it is JSON, not that it is an order (question 79).

Customising: toJSON() on a class controls how it is written, the second argument of JSON.stringify can filter keys, and the second argument of JSON.parse, a reviver function, can turn date strings back into Date objects.

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