Appearance
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 undefinedmap: one output for every input, so 3 in, 3 out.filter: keeps only the items where the function returnstrue.reduce:sumstarts at0, the second argument. Each step returns the new running total, which becomessumfor the next item.forEach: just runs the function. Its return value is alwaysundefined.
| Method | Returns | Use it to |
|---|---|---|
map | New array, same length | Transform each item |
filter | New array, same or shorter | Keep only some items |
reduce | Any single value | Total, group, count, build an object |
forEach | undefined | Run 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,reduceuses the first item as the start, and an empty array throwsTypeError: Reduce of empty array with no initial value. forEachcannot be stopped withbreakand does not wait forawaitinside it (question 57). Use afor...ofloop when you need either.find,someandeverystop early:findreturns the first match,someis true if any match,everyis 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 }- Reads a deep value safely. If
customeroraddressis missing, the chain stops and givesundefined, and??replaces it with'unknown'. - Calls a method only if it exists. Optional chaining also works for calls,
fn?.(), and indexes,items?.[0]. ??keeps0. Withorder.qty || 1, a real quantity of0would wrongly become1(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- Object destructuring:
total: amountrenames,status = 'new'sets a default used only when the value isundefined, andcustomer: { name }reaches into a nested object. - Array destructuring: by position. A blank skips an item, and
...otherscollects the rest. - In parameters, it gives named arguments with defaults, so the call reads clearly.
- Swapping two variables without a temporary one.
Traps:
- Destructuring
nullorundefinedthrows:const { id } = undefinedgivesTypeError. Use a default:function f({ id } = {}). - Defaults apply only for
undefined, not fornull. - 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- Merging objects: later keys win, so
optionsoverridesdefaults. - Combining arrays into a new array.
- 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' }- Rest parameter: every argument after
namelands in one array. It must be last. - 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 sharedSpread 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.
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- Shallow: a new outer object, but
itemsis the same array. - Deep:
structuredClonecopies every level, keeps dates, maps, sets and even circular references.
The ways to copy, compared:
| Method | Depth | Keeps dates, maps | Handles cycles | Copies functions |
|---|---|---|---|---|
{ ...obj }, Object.assign | Shallow | References only | n/a | References |
JSON.parse(JSON.stringify(obj)) | Deep | No: dates become strings | No: throws | No: dropped (question 49) |
structuredClone(obj) | Deep | Yes | Yes | No: throws |
A library, such as lodash cloneDeep | Deep | Yes | Yes | References |
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)
}- Fetches one page only when the consumer asks for more.
yield*hands out each item of the page one by one, pausing after each.returnends the generator: the nextnext()givesdone: true.for await...ofpulls items from an async generator.- 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:
| Use | Why |
|---|---|
| Lazy sequences | Values are produced only when asked for, even endless ones |
| Paging through APIs or big files | Memory stays small: one page at a time |
| Custom iteration for your own classes | Implement [Symbol.iterator] with function* |
| Pausable logic | The 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...in | for...of | |
|---|---|---|
| Gives | Keys, as strings | Values |
| Works on | Any object | Iterables: arrays, strings, Map, Set, generators |
| Inherited properties | Included, if enumerable | Not applicable |
| Plain objects | Yes | No: 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":{}}'| Value | After JSON.stringify |
|---|---|
Date | ISO string |
undefined, functions, symbols in objects | Dropped |
undefined in arrays | null |
NaN, Infinity | null |
Map, Set | {} |
| BigInt | Throws TypeError |
| Circular reference | Throws TypeError |
Coming back, dates do not return:
ts
const back = JSON.parse(JSON.stringify(order))
typeof back.placedAt // 'string', not a DateSafe 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)
}JSON.parsethrows on malformed input, such as a trailing comma, so wrap it.- 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.