JavaScript Coding Interview Questions with Solutions
Last updated 2026-11-19
JavaScript coding rounds mix algorithm problems with language-specific utilities that you would write in real projects: flatten an array, deep clone an object, build a throttle function, implement an event emitter. Interviewers watch for correct edge case handling and idiomatic modern syntax.
Each problem below has a worked solution that was run on current Node.js, with the stated output and complexity where it applies. Attempt each before reading, and then compare the edge cases you handled.
| Level | Fresher to 4 years |
|---|---|
| Focus | Utilities, string and array problems |
| Runtime | Node.js 18 or later |
Approach for each problem
State the inputs and edge cases, give the simple solution, then improve it if the complexity is poor. For utility functions, ask about this, arguments, sparse input and error handling before writing code.
- Use Map and Set for lookups
- Prefer pure functions that do not mutate their inputs
- Mention complexity at the end
More practice
Related reading: array methods and closures for the building blocks, DSA coding round tips for the algorithm side, and how to crack a JavaScript interview.
JavaScript Coding Interview Questions with Solutions: questions with worked answers
1 Reverse a string and check if it is a palindrome.
easyStrings are immutable, so split into characters, reverse and join. For a palindrome, normalise by lowercasing and removing non-alphanumeric characters, then compare with the reversed string, or use two pointers to avoid the extra copy. Time is O(n), space O(n) for the copy version. Spread over a string handles surrogate pairs better than split with an empty string.
javascriptconst reverse = (s) => [...s].reverse().join(""); const isPal = (s) => { const t = s.toLowerCase().replace(/[^a-z0-9]/g, ""); return t === reverse(t); }; console.log(reverse("hello")); // olleh console.log(isPal("A man, a plan, a canal: Panama")); // true2 Two Sum: return the indices of two numbers that add to a target.
easyScan once, storing each value's index in a Map. For each number check whether the complement was seen. O(n) time and O(n) space, instead of O(n squared) for the nested loops.
javascriptfunction twoSum(nums, target) { const seen = new Map(); for (let i = 0; i < nums.length; i++) { const need = target - nums[i]; if (seen.has(need)) return [seen.get(need), i]; seen.set(nums[i], i); } return []; } console.log(twoSum([2, 7, 11, 15], 9)); // [ 0, 1 ]3 Count the frequency of each character or word.
easyIterate and increment counts in a Map or object. A Map is safer for arbitrary keys because it has no inherited properties. Sorting the entries by count gives the most frequent items. O(n) time.
javascriptconst freq = (s) => { const m = new Map(); for (const ch of s) m.set(ch, (m.get(ch) ?? 0) + 1); return m; }; console.log([...freq("banana")]); // [ [ 'b', 1 ], [ 'a', 3 ], [ 'n', 2 ] ]4 Group anagrams.
mediumUse the sorted characters of each word as a canonical key and group in a Map. For n words of length k the cost is O(n k log k). A count-based key would make it O(n k).
javascriptfunction groupAnagrams(words) { const map = new Map(); for (const w of words) { const key = [...w].sort().join(""); if (!map.has(key)) map.set(key, []); map.get(key).push(w); } return [...map.values()]; } console.log(groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"])); // [ [ 'eat', 'tea', 'ate' ], [ 'tan', 'nat' ], [ 'bat' ] ]5 Flatten a nested array without using flat.
mediumRecurse: for each item, if it is an array, flatten it and spread, else push it. An iterative version uses an explicit stack and avoids deep recursion limits. Both are O(n) in the total number of elements.
javascriptconst flatten = (a) => a.reduce((out, x) => (Array.isArray(x) ? out.concat(flatten(x)) : [...out, x]), []); console.log(flatten([1, [2, [3, [4]], 5]])); // [ 1, 2, 3, 4, 5 ] function flatIter(a) { const st = [...a], out = []; while (st.length) { const x = st.pop(); Array.isArray(x) ? st.push(...x) : out.push(x); } return out.reverse(); } console.log(flatIter([1, [2, [3]]])); // [ 1, 2, 3 ]6 Write a deep clone function.
mediumIn production use structuredClone. For the interview version, handle primitives, arrays, plain objects, Dates and circular references with a WeakMap that remembers already-cloned objects. Functions are returned as they are. JSON.parse and stringify is a shortcut that fails on Dates, undefined, Maps and cycles.
javascriptfunction deepClone(v, seen = new WeakMap()) { if (v === null || typeof v !== "object") return v; if (v instanceof Date) return new Date(v); if (seen.has(v)) return seen.get(v); const out = Array.isArray(v) ? [] : {}; seen.set(v, out); for (const k of Object.keys(v)) out[k] = deepClone(v[k], seen); return out; } const a = { n: [1, { x: 2 }] }; a.self = a; const b = deepClone(a); console.log(b !== a, b.self === b, b.n[1] !== a.n[1]); // true true true7 Write a throttle function.
mediumThrottle ensures a function runs at most once per interval. Record the time of the last run and ignore calls that arrive sooner. A trailing-call version also schedules the final call. It suits scroll and resize handlers, whereas debounce waits for a pause.
javascriptfunction throttle(fn, wait) { let last = 0; return function (...args) { const now = Date.now(); if (now - last >= wait) { last = now; return fn.apply(this, args); } }; } const t = throttle((x) => console.log("call", x), 100); t(1); t(2); t(3); // call 1 only8 Implement pipe and compose.
mediumpipe applies functions left to right, compose right to left. Both are a reduce over the list of functions with the input as the initial value.
javascriptconst pipe = (...fns) => (x) => fns.reduce((v, f) => f(v), x); const compose = (...fns) => (x) => fns.reduceRight((v, f) => f(v), x); const inc = (x) => x + 1, dbl = (x) => x * 2; console.log(pipe(inc, dbl)(5), compose(inc, dbl)(5)); // 12 119 Chunk an array into pieces of size n.
easyStep through the array by n and slice. O(n) time. Validate that n is a positive integer, since a zero step would loop forever.
javascriptconst chunk = (a, n) => { const out = []; for (let i = 0; i < a.length; i += n) out.push(a.slice(i, i + n)); return out; }; console.log(chunk([1, 2, 3, 4, 5], 2)); // [ [ 1, 2 ], [ 3, 4 ], [ 5 ] ]10 Flatten a nested object into dot-separated keys.
mediumRecurse through own keys, building a path prefix, and assign leaf values to the result. Treat arrays as leaves or index them, depending on the requirement, and say which you chose.
javascriptfunction flattenObj(o, prefix = "", out = {}) { for (const [k, v] of Object.entries(o)) { const key = prefix ? `${prefix}.${k}` : k; if (v && typeof v === "object" && !Array.isArray(v)) flattenObj(v, key, out); else out[key] = v; } return out; } console.log(flattenObj({ a: 1, b: { c: 2, d: { e: 3 } } })); // { a: 1, 'b.c': 2, 'b.d.e': 3 }11 Check for balanced brackets.
mediumPush openers on a stack. For a closer, the stack top must be its matching opener. At the end the stack must be empty. O(n) time and O(n) space.
javascriptfunction balanced(s) { const pairs = { ")": "(", "]": "[", "}": "{" }, st = []; for (const ch of s) { if (ch in pairs) { if (st.pop() !== pairs[ch]) return false; } else if ("([{".includes(ch)) st.push(ch); } return st.length === 0; } console.log(balanced("{[()]}"), balanced("(]"), balanced("((")); // true false false12 Implement binary search and find the first position of a target in a sorted array with duplicates.
mediumKeep lo and hi. When the middle equals the target, record it and keep searching left to find the first occurrence. O(log n) time and O(1) space.
javascriptfunction firstIndex(a, x) { let lo = 0, hi = a.length - 1, ans = -1; while (lo <= hi) { const mid = (lo + hi) >> 1; if (a[mid] === x) { ans = mid; hi = mid - 1; } else if (a[mid] < x) lo = mid + 1; else hi = mid - 1; } return ans; } console.log(firstIndex([1, 2, 2, 2, 5], 2), firstIndex([1, 3], 2)); // 1 -113 Implement a simple event emitter.
hardKeep a Map from event names to arrays of listeners. on adds a listener, off removes it, once wraps a listener that removes itself after one call, and emit calls every listener with the arguments. Copy the listener array before iterating so that listeners removed during emit do not skip others.
javascriptclass Emitter { #h = new Map(); on(e, f) { (this.#h.get(e) ?? this.#h.set(e, []).get(e)).push(f); return this; } off(e, f) { this.#h.set(e, (this.#h.get(e) ?? []).filter((x) => x !== f)); return this; } once(e, f) { const w = (...a) => { this.off(e, w); f(...a); }; return this.on(e, w); } emit(e, ...a) { [...(this.#h.get(e) ?? [])].forEach((f) => f(...a)); } } const em = new Emitter(); em.once("hi", (n) => console.log("hello", n)); em.emit("hi", 1); em.emit("hi", 2); // hello 114 Deep equality check of two values.
hardCompare primitives with Object.is. For objects, check that both are non-null objects with the same keys count, and recursively compare each key, treating arrays like objects with index keys. Mention the cases not handled: Dates, Maps, Sets and cycles.
javascriptfunction deepEqual(a, b) { if (Object.is(a, b)) return true; if (typeof a !== "object" || typeof b !== "object" || !a || !b) return false; const ka = Object.keys(a), kb = Object.keys(b); return ka.length === kb.length && ka.every((k) => k in b && deepEqual(a[k], b[k])); } console.log(deepEqual({ a: [1, { b: 2 }] }, { a: [1, { b: 2 }] })); // true console.log(deepEqual({ a: 1 }, { a: 1, b: undefined })); // false
Frequently asked questions
Which JavaScript coding questions are asked most?
Array and string manipulation, two sum and its variants, debounce and throttle, flatten, deep clone, promise utilities, currying and event emitters.
Should I use built-in methods or write loops?
Use built-ins for clarity unless the interviewer asks you to implement them. Say which built-in you would use in real code.
How do I handle edge cases?
Ask about empty input, duplicates, negative numbers, non-integers and very large input before coding, and test your function on them out loud.
Are TypeScript solutions acceptable?
Usually yes if the platform allows it. Otherwise write plain JavaScript and mention types in comments.
Related guides
More in Programming Language Interview Questions by Language
- JavaScript DOM Interview Questions
- JavaScript ES6 Interview Questions
- JavaScript Event Loop Interview Questions
- JavaScript Hoisting and Scope Interview Questions
- JavaScript Interview Questions and Answers
- JavaScript Promises and Async/Await Interview Questions
- JavaScript Prototypes and Inheritance Interview Questions
- JavaScript this Keyword Interview Questions
- JVM Internals Interview Questions
- MySQL Interview Questions and Answers
- Nth Highest Salary in SQL: Interview Questions
- PL/SQL Interview Questions and Answers