{jsonbody.com}

Top 30 JavaScript Coding Interview Questions

Top 30 JavaScript coding interview questions with solutions: strings, arrays, closures, debounce, throttle, deep clone, promises and polyfills explained.

Loading…

Strings

Q1. Reverse a string

Problem: Write a function that returns a string reversed.

function reverse(str) {
  return [...str].reverse().join("");
}

reverse("hello"); // "olleh"

Explanation: Spreading into an array splits the string by Unicode code points, so emoji stay intact, unlike str.split(""). Then reverse the array and join it back.

Q2. Check whether a string is a palindrome

Problem: Return true if a string reads the same backwards, ignoring case and non-alphanumeric characters.

function isPalindrome(str) {
  const clean = str.toLowerCase().replace(/[^a-z0-9]/g, "");
  let left = 0, right = clean.length - 1;
  while (left < right) {
    if (clean[left++] !== clean[right--]) return false;
  }
  return true;
}

isPalindrome("A man, a plan, a canal: Panama"); // true

Explanation: Normalise the string, then compare characters from both ends moving inward. Two pointers use O(1) extra space after cleaning.

Q3. Check whether two strings are anagrams

Problem: Return true if two strings contain the same letters in any order.

function isAnagram(a, b) {
  if (a.length !== b.length) return false;
  const count = {};
  for (const ch of a) count[ch] = (count[ch] || 0) + 1;
  for (const ch of b) {
    if (!count[ch]) return false;
    count[ch]--;
  }
  return true;
}

isAnagram("listen", "silent"); // true

Explanation: Count each character of the first string, then subtract for the second. Any missing or extra character fails. This is O(n), faster than sorting both strings.

Q4. Find the first non-repeating character

Problem: Return the first character that appears only once in a string, or null.

function firstUnique(str) {
  const count = new Map();
  for (const ch of str) count.set(ch, (count.get(ch) || 0) + 1);
  for (const ch of str) if (count.get(ch) === 1) return ch;
  return null;
}

firstUnique("swiss"); // "w"

Explanation: The first pass counts characters, the second finds the first with a count of one. A Map keeps the code clear for any character.

Q5. Capitalize the first letter of each word

Problem: Convert "hello world" to "Hello World".

function titleCase(str) {
  return str
    .split(" ")
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
    .join(" ");
}

titleCase("hello WORLD"); // "Hello World"

Explanation: Split into words, uppercase the first character and lowercase the rest, then join with spaces.

Q6. Count vowels in a string

Problem: Return how many vowels a string contains.

function countVowels(str) {
  return (str.match(/[aeiou]/gi) || []).length;
}

countVowels("JavaScript"); // 3

Explanation: A global, case-insensitive regex returns every vowel match. match returns null when nothing matches, so default to an empty array.

Arrays

Q7. Remove duplicates from an array

Problem: Return a new array with only unique values.

const unique = (arr) => [...new Set(arr)];

unique([1, 2, 2, 3, 1]); // [1, 2, 3]

Explanation: A Set keeps only unique values and preserves insertion order. Spreading it gives back an array in O(n) time.

Q8. Flatten a nested array

Problem: Flatten [1, [2, [3, [4]]]] into [1, 2, 3, 4] without using flat().

function flatten(arr) {
  return arr.reduce(
    (acc, item) => acc.concat(Array.isArray(item) ? flatten(item) : item),
    []
  );
}

flatten([1, [2, [3, [4]]]]); // [1, 2, 3, 4]

Explanation: Recursively flatten nested arrays and concatenate plain values. Built-in arr.flat(Infinity) does the same, but interviewers usually ask for the manual version.

Q9. Find the largest and second largest numbers

Problem: Return the two largest distinct numbers in one pass.

function topTwo(nums) {
  let first = -Infinity, second = -Infinity;
  for (const n of nums) {
    if (n > first) {
      second = first;
      first = n;
    } else if (n > second && n < first) {
      second = n;
    }
  }
  return [first, second];
}

topTwo([10, 5, 20, 8, 20]); // [20, 10]

Explanation: Track the top two values while scanning once. The n < first check skips duplicates of the maximum, so the second value stays distinct.

Q10. Two Sum

Problem: Given an array and a target, return the indexes of two numbers that add up to the target.

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 [];
}

twoSum([2, 7, 11, 15], 9); // [0, 1]

Explanation: Store each number's index in a map. For each item, check whether its complement was already seen. This is O(n) instead of the O(n²) nested loop.

Q11. Chunk an array

Problem: Split an array into groups of a given size.

function chunk(arr, size) {
  const result = [];
  for (let i = 0; i < arr.length; i += size) {
    result.push(arr.slice(i, i + size));
  }
  return result;
}

chunk([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]]

Explanation: Step through the array by size and slice each group. The last group holds whatever remains.

Q12. Group objects by a property

Problem: Group an array of objects by a key, such as category.

function groupBy(items, key) {
  return items.reduce((groups, item) => {
    (groups[item[key]] ||= []).push(item);
    return groups;
  }, {});
}

groupBy([{ type: "a" }, { type: "b" }, { type: "a" }], "type");
// { a: [{...}, {...}], b: [{...}] }

Explanation: Use reduce to build an object of arrays. ||= creates the array on first use. Modern runtimes also offer Object.groupBy(items, fn).

Q13. Find the missing number

Problem: An array holds numbers from 1 to n with one missing. Find it.

function missingNumber(nums) {
  const n = nums.length + 1;
  const expected = (n * (n + 1)) / 2;
  return expected - nums.reduce((sum, x) => sum + x, 0);
}

missingNumber([1, 2, 4, 5]); // 3

Explanation: The sum of 1 to n is n(n+1)/2. Subtracting the actual sum gives the missing number in O(n) time and O(1) space.

Q14. Rotate an array by k steps

Problem: Rotate an array to the right by k positions.

function rotate(arr, k) {
  const n = arr.length;
  k = k % n;
  return [...arr.slice(n - k), ...arr.slice(0, n - k)];
}

rotate([1, 2, 3, 4, 5], 2); // [4, 5, 1, 2, 3]

Explanation: Taking k % n handles k larger than the length. The last k items move to the front.

Q15. Find the intersection of two arrays

Problem: Return the values that appear in both arrays, without duplicates.

function intersection(a, b) {
  const setB = new Set(b);
  return [...new Set(a)].filter((x) => setB.has(x));
}

intersection([1, 2, 2, 3], [2, 3, 4]); // [2, 3]

Explanation: Putting one array in a Set makes each lookup O(1), so the whole check is O(n + m) instead of nested loops.

Q16. Move all zeros to the end

Problem: Move every 0 to the end of an array in place, keeping the order of other items.

function moveZeros(nums) {
  let insert = 0;
  for (const n of nums) if (n !== 0) nums[insert++] = n;
  while (insert < nums.length) nums[insert++] = 0;
  return nums;
}

moveZeros([0, 1, 0, 3, 12]); // [1, 3, 12, 0, 0]

Explanation: Copy non-zero values forward with a write pointer, then fill the rest with zeros. It is one pass and uses no extra array.

Functions & Closures

Q17. Implement debounce

Problem: Write debounce(fn, delay) so fn runs only after calls stop for delay milliseconds.

function debounce(fn, delay) {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}

const onSearch = debounce((q) => console.log("search", q), 300);

Explanation: Each call clears the pending timer and starts a new one, so only the last call in a burst runs. The closure keeps timer between calls, and apply keeps this and the arguments.

Q18. Implement throttle

Problem: Write throttle(fn, limit) so fn runs at most once every limit milliseconds.

function throttle(fn, limit) {
  let last = 0;
  return function (...args) {
    const now = Date.now();
    if (now - last >= limit) {
      last = now;
      fn.apply(this, args);
    }
  };
}

window.addEventListener("scroll", throttle(() => console.log("scroll"), 200));

Explanation: Remember when the function last ran and ignore calls inside the window. This version runs on the leading edge.

Q19. Implement memoize

Problem: Cache a function's results by its arguments.

function memoize(fn) {
  const cache = new Map();
  return function (...args) {
    const key = JSON.stringify(args);
    if (!cache.has(key)) cache.set(key, fn.apply(this, args));
    return cache.get(key);
  };
}

const slowSquare = (n) => n * n;
const fastSquare = memoize(slowSquare);

Explanation: The closure keeps a cache keyed by the serialised arguments. Repeated calls return the stored result. JSON.stringify works for simple arguments only.

Q20. Implement once

Problem: Return a function that runs fn only the first time and returns that result afterwards.

function once(fn) {
  let called = false, result;
  return function (...args) {
    if (!called) {
      called = true;
      result = fn.apply(this, args);
    }
    return result;
  };
}

const init = once(() => console.log("init"));
init(); init(); // logs once

Explanation: A flag in the closure records whether the function has run, and the first result is stored for later calls.

Q21. Implement currying

Problem: Write curry(fn) so curry(add)(1)(2)(3) works for a three-argument add.

function curry(fn) {
  return function curried(...args) {
    if (args.length >= fn.length) return fn.apply(this, args);
    return (...next) => curried.apply(this, [...args, ...next]);
  };
}

const add = (a, b, c) => a + b + c;
curry(add)(1)(2)(3); // 6
curry(add)(1, 2)(3); // 6

Explanation: Collect arguments until there are as many as the function declares (fn.length), then call it. Otherwise return a function that collects more.

Q22. Polyfill Function.prototype.bind

Problem: Write your own myBind that works like bind.

Function.prototype.myBind = function (context, ...preset) {
  const fn = this;
  return function (...args) {
    return fn.apply(context, [...preset, ...args]);
  };
};

const greet = function (greeting) { return greeting + ", " + this.name; };
greet.myBind({ name: "Asha" }, "Hi")(); // "Hi, Asha"

Explanation: Inside the method, this is the original function. Return a wrapper that calls it with the fixed context and preset arguments, plus any new ones.

Objects & Promises

Q23. Deep clone an object

Problem: Copy an object with nested objects and arrays so changes to the copy do not affect the original.

function deepClone(value) {
  if (value === null || typeof value !== "object") return value;
  if (Array.isArray(value)) return value.map(deepClone);
  const copy = {};
  for (const key of Object.keys(value)) copy[key] = deepClone(value[key]);
  return copy;
}

// Built-in alternative: structuredClone(value)

Explanation: Return primitives as they are, then recursively copy arrays and plain objects. structuredClone also handles dates, maps and circular references.

Q24. Deep compare two objects

Problem: Return true if two values are deeply equal.

function deepEqual(a, b) {
  if (a === b) return true;
  if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
  const keysA = Object.keys(a), keysB = Object.keys(b);
  if (keysA.length !== keysB.length) return false;
  return keysA.every((key) => deepEqual(a[key], b[key]));
}

deepEqual({ x: [1, 2] }, { x: [1, 2] }); // true

Explanation: Equal references or primitives match at once. Otherwise both must be objects with the same keys, and each value must be deeply equal.

Q25. Polyfill Promise.all

Problem: Write promiseAll(promises) that resolves with all results in order or rejects on the first failure.

function promiseAll(promises) {
  return new Promise((resolve, reject) => {
    const results = [];
    let done = 0;
    if (promises.length === 0) return resolve(results);
    promises.forEach((p, i) => {
      Promise.resolve(p).then((value) => {
        results[i] = value;
        if (++done === promises.length) resolve(results);
      }, reject);
    });
  });
}

Explanation: Store each result at its own index so order is kept, count completions, and resolve when all finish. The first rejection rejects the whole promise. Promise.resolve also accepts plain values.

Q26. Implement sleep

Problem: Write sleep(ms) that can be awaited.

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function demo() {
  console.log("start");
  await sleep(1000);
  console.log("one second later");
}

Explanation: Wrap setTimeout in a promise that resolves after the delay, so await pauses the async function without blocking the thread.

Q27. Retry a failing async function

Problem: Retry a function that returns a promise up to n times.

async function retry(fn, times = 3, delay = 500) {
  for (let attempt = 1; attempt <= times; attempt++) {
    try {
      return await fn();
    } catch (err) {
      if (attempt === times) throw err;
      await new Promise((r) => setTimeout(r, delay * attempt));
    }
  }
}

retry(() => fetch("/api/data"));

Explanation: Try the function in a loop and rethrow only after the last attempt. Waiting longer after each failure (backoff) avoids hammering a struggling service.

Q28. Run async tasks with a concurrency limit

Problem: Run an array of async task functions with at most limit running at once.

async function runWithLimit(tasks, limit) {
  const results = [];
  let next = 0;
  async function worker() {
    while (next < tasks.length) {
      const i = next++;
      results[i] = await tasks[i]();
    }
  }
  await Promise.all(Array.from({ length: limit }, worker));
  return results;
}

Explanation: Start limit workers that each take the next task until none remain. Since JavaScript runs one piece of code at a time, next++ is safe to share between workers.

Q29. Implement an event emitter

Problem: Build a class with on, off and emit.

class EventEmitter {
  constructor() { this.events = {}; }
  on(name, fn) {
    (this.events[name] ||= []).push(fn);
    return () => this.off(name, fn);
  }
  off(name, fn) {
    this.events[name] = (this.events[name] || []).filter((f) => f !== fn);
  }
  emit(name, ...args) {
    (this.events[name] || []).forEach((fn) => fn(...args));
  }
}

Explanation: Keep an array of listeners per event name. on returns an unsubscribe function, a common follow-up request.

Q30. Get a nested value safely

Problem: Write get(obj, path) that reads "a.b.c" and returns undefined if any part is missing.

function get(obj, path, fallback) {
  const value = path.split(".").reduce((cur, key) => cur?.[key], obj);
  return value === undefined ? fallback : value;
}

get({ a: { b: { c: 42 } } }, "a.b.c"); // 42
get({}, "a.b", "none"); // "none"

Explanation: Walk the path one key at a time with optional chaining, which stops at undefined instead of throwing, and fall back to a default.