Autocoder

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.

LevelFresher to 4 years
FocusUtilities, string and array problems
RuntimeNode.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.

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. 1

    Reverse a string and check if it is a palindrome.

    easy

    Strings 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.

    javascript
    const 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"));  // true
  2. 2

    Two Sum: return the indices of two numbers that add to a target.

    easy

    Scan 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.

    javascript
    function 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. 3

    Count the frequency of each character or word.

    easy

    Iterate 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.

    javascript
    const 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. 4

    Group anagrams.

    medium

    Use 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).

    javascript
    function 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. 5

    Flatten a nested array without using flat.

    medium

    Recurse: 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.

    javascript
    const 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. 6

    Write a deep clone function.

    medium

    In 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.

    javascript
    function 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 true
  7. 7

    Write a throttle function.

    medium

    Throttle 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.

    javascript
    function 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 only
  8. 8

    Implement pipe and compose.

    medium

    pipe 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.

    javascript
    const 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 11
  9. 9

    Chunk an array into pieces of size n.

    easy

    Step through the array by n and slice. O(n) time. Validate that n is a positive integer, since a zero step would loop forever.

    javascript
    const 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. 10

    Flatten a nested object into dot-separated keys.

    medium

    Recurse 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.

    javascript
    function 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. 11

    Check for balanced brackets.

    medium

    Push 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.

    javascript
    function 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 false
  12. 12

    Implement binary search and find the first position of a target in a sorted array with duplicates.

    medium

    Keep 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.

    javascript
    function 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 -1
  13. 13

    Implement a simple event emitter.

    hard

    Keep 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.

    javascript
    class 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 1
  14. 14

    Deep equality check of two values.

    hard

    Compare 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.

    javascript
    function 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

See all in this section