Interview Q&A · JavaScript · 14 questions in this topic
Common Coding Tasks — JavaScript Interview Q&A
Implement-it-now favorites — flattening, grouping, debounce, deep equality and promise utilities. Part of Tricky Outputs & Coding Tasks · 204 questions in the JavaScript bank.
How do you reverse a string (Unicode-safe)?
Answer
Spread by code points ([...s]) then reverse-join — length-based indexing breaks emoji (surrogate pairs). Grapheme clusters (family emoji) need Intl.Segmenter for full correctness.
Code-points-not-units is the correctness rule.
Example
const rev = (s) => [...s].reverse().join(''); rev('hello'); // 'olleh'
How do you check anagrams?
Answer
Normalize (case), frequency-count one string, verify with the other — O(n). Sorting both (O(n log n)) is the simpler alternative. Early-exit on length mismatch.
Count-then-verify is the linear pattern.
Example
function anagram(a, b) { if (a.length !== b.length) return false; const c = {}; for (const ch of a.toLowerCase()) c[ch] = (c[ch] || 0) + 1; for (const ch of b.toLowerCase()) if (!c[ch]--) return false; return true; }
How do you dedupe an array (and by key)?
Answer
Primitives: [...new Set(arr)]. Objects by key: Map keyed on the key field, keep first. SameValueZero makes NaN dedupe correctly under Set.
Set-for-values, Map-by-key-for-entities.
Example
const uniq = [...new Set([1, 1, NaN, NaN])]; // [1, NaN] // by key: new Map(users.map((u) => [u.id, u]))
How do you implement two-sum (return indices)?
Answer
One pass with a Map value→index: look for complement first (avoids self-match), store after. O(n) time and space.
Lookup-before-store is the ordering detail.
Example
function twoSum(a, t) { const at = new Map(); for (let i = 0; i < a.length; i++) { if (at.has(t - a[i])) return [at.get(t - a[i]), i]; at.set(a[i], i); } }
How do you flatten nested arrays (any depth)?
Answer
arr.flat(Infinity) natively; recursive reduce-concat by hand (Array.isArray check); iterative stack version avoids recursion limits. Depth parameter controls levels.
Native-flat-first, recursive-for-teaching.
Example
const flat = (a) => a.reduce((r, x) => r.concat(Array.isArray(x) ? flat(x) : x), []);
How do you group an array by a key?
Answer
Object.groupBy (ES2024) natively; reduce-to-object fallback; Map variant for non-string keys. Null-prototype results dodge __proto__ collisions.
groupBy-native, reduce-fallback is the pairing.
Example
// Object.groupBy(users, (u) => u.dept) // fallback: reduce with (m[k] ||= []).push(v)
How do you implement debounce (with leading/trailing)?
Answer
Reset a timer per call; fire on quiet (trailing) or immediately-then-lockout (leading). Clear prior timer each invocation; expose cancel/flush for control.
Timer-reset-per-call is the mechanism.
Example
const debounce = (fn, ms) => { let t; const d = (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); }; d.cancel = () => clearTimeout(t); return d; };
How do you implement throttle?
Answer
Gate with last-run timestamp (or in-flight flag): run if interval elapsed, else schedule trailing. Timestamp-compare is simplest; timer-flag variants handle trailing precisely.
Gate-on-elapsed is the throttle core.
Example
const throttle = (fn, ms) => { let last = 0; return (...a) => { const now = Date.now(); if (now - last >= ms) { last = now; fn(...a); } }; };
How do you deep-equal two values?
Answer
Recurse with type checks (Array vs object), key-set comparison, cycle guards (seen-pairs), and specials (Date/RegExp/Map/Set/NaN via Object.is). Libraries (lodash.isEqual) cover the long tail.
Cycles-plus-specials is what separates robust from naive.
Example
// Object.is(a, b) fast path; recurse keys with seen-pair set; // Dates by getTime, NaN via Object.is
💡 Mention cycles first — interviewers probe them immediately.
How do you implement `Promise.all` (simplified)?
Answer
Map inputs to promises, collect by index, count fulfillments, resolve ordered array at N, reject fast on first error. Empty input resolves [].
Index-ordered-plus-fail-fast is the spec in miniature.
Example
function all(ps) { return new Promise((res, rej) => { const out = []; let n = 0; ps.forEach((p, i) => Promise.resolve(p).then( (v) => { out[i] = v; if (++n === ps.length) res(out); }, rej ) ); if (ps.length === 0) res([]); }); }
How do you detect a cycle in a linked structure (JS objects)?
Answer
Visited-set traversal (O(n) space) or Floyd tortoise-hare on next-chains (O(1) space). JSON.stringify throws on cycles — the built-in detector. structuredClone preserves them.
Floyd-for-chains, sets-for-graphs.
Example
// try { JSON.stringify(x); } catch { /* cyclic */ }How do you chunk an array into groups of N?
Answer
Slice in steps (simple, O(n)), or reduce-accumulate. Generator versions stream chunks lazily for huge inputs.
Slice-steps is the readable default.
Example
const chunk = (a, n) => Array.from({ length: Math.ceil(a.length / n) }, (_, i) => a.slice(i * n, i * n + n) );
How do you implement a tiny event emitter?
Answer
Map event→listener-set with on/off/once/emit; once wraps self-removing handlers; emit copies the set before iterating (mutation-during-emit safety).
Copy-before-iterate is the robustness detail.
Example
class Emitter { map = new Map(); on(e, fn) { (this.map.get(e) || this.map.set(e, new Set()).get(e)).add(fn); } emit(e, ...a) { for (const fn of [...(this.map.get(e) || [])]) fn(...a); } }
How do you memoize with cache limits (LRU sketch)?
Answer
Map insertion-order as recency (delete+re-set on hit moves to newest), evict oldest past capacity. Unbounded memoization on unique inputs leaks — capacity is correctness.
Capacity-plus-recency is the LRU sketch.
Example
// get: hit → delete+set (newest); set: evict map.keys().next() past capRecommended resourcesAffiliate links · may earn us a commission