Top 30 JavaScript coding interview questions with step-by-step solutions. Covers arrays, strings, objects, recursion, algorithms, and problem-solving patterns for 2026 interviews.
These coding questions test problem-solving ability, not just JavaScript knowledge. They appear in real interviews at product companies, startups, and big tech.
Section 1: Array Problems
Q1: Flatten a Nested Array
// Implement: flattenArray([[1, [2, [3, [4]]]], 5]) → [1, 2, 3, 4, 5]
function flattenArray(arr) {
return arr.reduce((acc, item) => {
if (Array.isArray(item)) {
return acc.concat(flattenArray(item));
}
return acc.concat(item);
}, []);
}
console.log(flattenArray([1, [2, [3, [4]]]]));
console.log(flattenArray([[1, 2], [3, [4, 5]]]));
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
Alternative using built-in:
[1, [2, [3]]].flat(Infinity); // Native ES2019+
Q2: Remove Duplicates from Array
function unique(arr) {
return [...new Set(arr)];
}
// Using filter:
function uniqueFilter(arr) {
return arr.filter((item, index) => arr.indexOf(item) === index);
}
console.log(unique([1, 2, 2, 3, 3, 4, 1]));
console.log(unique(["a", "b", "a", "c"]));
[1, 2, 3, 4]
["a", "b", "c"]
Q3: Chunk Array
function chunk(arr, size) {
const result = [];
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
}
console.log(chunk([1, 2, 3, 4, 5], 2));
console.log(chunk([1, 2, 3, 4, 5], 3));
[[1, 2], [3, 4], [5]]
[[1, 2, 3], [4, 5]]
Q4: Two Sum
function twoSum(nums, target) {
const map = new Map();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (map.has(complement)) {
return [map.get(complement), i];
}
map.set(nums[i], i);
}
return null;
}
console.log(twoSum([2, 7, 11, 15], 9));
console.log(twoSum([3, 2, 4], 6));
Time: O(n) | Space: O(n)
Q5: Group By Key
function groupBy(arr, key) {
return arr.reduce((groups, item) => {
const group = item[key];
groups[group] = groups[group] || [];
groups[group].push(item);
return groups;
}, {});
}
const people = [
{ name: "Alice", city: "Delhi" },
{ name: "Bob", city: "Mumbai" },
{ name: "Carol", city: "Delhi" }
];
console.log(groupBy(people, "city"));
{
Delhi: [{ name: "Alice", city: "Delhi" }, { name: "Carol", city: "Delhi" }],
Mumbai: [{ name: "Bob", city: "Mumbai" }]
}
Section 2: String Problems
Q6: Check Palindrome
function isPalindrome(str) {
const clean = str.toLowerCase().replace(/[^a-z0-9]/g, "");
return clean === clean.split("").reverse().join("");
}
console.log(isPalindrome("racecar")); // true
console.log(isPalindrome("A man a plan a canal Panama")); // true
console.log(isPalindrome("hello")); // false
Q7: Check Anagram
function isAnagram(s, t) {
if (s.length !== t.length) return false;
const count = {};
for (const char of s) count[char] = (count[char] || 0) + 1;
for (const char of t) {
if (!count[char]) return false;
count[char]--;
}
return true;
}
console.log(isAnagram("listen", "silent")); // true
console.log(isAnagram("hello", "world")); // false
Q8: Count Character Frequency
function charFrequency(str) {
return str.split("").reduce((acc, char) => {
acc[char] = (acc[char] || 0) + 1;
return acc;
}, {});
}
console.log(charFrequency("javascript"));
{ j: 1, a: 2, v: 1, s: 1, c: 1, r: 1, i: 1, p: 1, t: 1 }
Q9: Capitalize Words
function titleCase(str) {
return str
.split(" ")
.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join(" ");
}
console.log(titleCase("hello world from javascript"));
Hello World From Javascript
Q10: Find Longest Word
function longestWord(sentence) {
return sentence
.split(" ")
.reduce((longest, word) =>
word.length > longest.length ? word : longest, "");
}
console.log(longestWord("The quick brown fox jumped"));
Section 3: Object Problems
Q11: Deep Clone an Object
function deepClone(obj) {
if (obj === null || typeof obj !== "object") return obj;
if (obj instanceof Date) return new Date(obj.getTime());
if (Array.isArray(obj)) return obj.map(item => deepClone(item));
const clone = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
clone[key] = deepClone(obj[key]);
}
}
return clone;
}
const original = { a: 1, b: { c: 2, d: [3, 4] } };
const cloned = deepClone(original);
cloned.b.c = 99;
console.log(original.b.c); // 2 (untouched)
console.log(cloned.b.c); // 99
Q12: Flatten a Nested Object
function flattenObject(obj, prefix = "") {
return Object.keys(obj).reduce((acc, key) => {
const fullKey = prefix ? `${prefix}.${key}` : key;
if (typeof obj[key] === "object" && obj[key] !== null && !Array.isArray(obj[key])) {
Object.assign(acc, flattenObject(obj[key], fullKey));
} else {
acc[fullKey] = obj[key];
}
return acc;
}, {});
}
const nested = { a: { b: { c: 1 }, d: 2 }, e: 3 };
console.log(flattenObject(nested));
{ "a.b.c": 1, "a.d": 2, e: 3 }
Q13: Object to Query String
function toQueryString(params) {
return Object.entries(params)
.map(([key, val]) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`)
.join("&");
}
console.log(toQueryString({ name: "Alice", age: 25, city: "New Delhi" }));
name=Alice&age=25&city=New%20Delhi
Section 4: Function Problems
Q14: Custom map()
Array.prototype.myMap = function (callback) {
const result = [];
for (let i = 0; i < this.length; i++) {
result.push(callback(this[i], i, this));
}
return result;
};
console.log([1, 2, 3].myMap(x => x * 2));
console.log([1, 2, 3].myMap((x, i) => `${i}:${x}`));
[2, 4, 6]
["0:1", "1:2", "2:3"]
Q15: Custom filter()
Array.prototype.myFilter = function (callback) {
const result = [];
for (let i = 0; i < this.length; i++) {
if (callback(this[i], i, this)) {
result.push(this[i]);
}
}
return result;
};
console.log([1, 2, 3, 4, 5].myFilter(x => x % 2 === 0));
Q16: Custom reduce()
Array.prototype.myReduce = function (callback, initialValue) {
let acc = initialValue !== undefined ? initialValue : this[0];
const start = initialValue !== undefined ? 0 : 1;
for (let i = start; i < this.length; i++) {
acc = callback(acc, this[i], i, this);
}
return acc;
};
console.log([1, 2, 3, 4].myReduce((acc, val) => acc + val, 0));
console.log([1, 2, 3, 4].myReduce((acc, val) => acc * val));
Q17: Debounce Function
function debounce(fn, delay) {
let timer = null;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
timer = null;
}, delay);
};
}
const handleInput = debounce((val) => console.log("Search:", val), 300);
// Only calls search after 300ms of inactivity
Q18: Throttle Function
function throttle(fn, limit) {
let lastRun = 0;
return function (...args) {
const now = Date.now();
if (now - lastRun >= limit) {
lastRun = now;
return fn.apply(this, args);
}
};
}
const handleScroll = throttle(() => console.log("Scrolled!"), 100);
// At most once per 100ms
Q19: Function Composition
const compose = (...fns) => (x) => fns.reduceRight((acc, fn) => fn(acc), x);
const pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x);
const double = x => x * 2;
const addOne = x => x + 1;
const square = x => x * x;
const transform = compose(square, addOne, double);
console.log(transform(3)); // square(addOne(double(3))) = square(7) = 49
const pipeline = pipe(double, addOne, square);
console.log(pipeline(3)); // square(addOne(double(3))) = same
Q20: Curry Function
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
}
return function (...more) {
return curried.apply(this, args.concat(more));
};
};
}
const add = (a, b, c) => a + b + c;
const curriedAdd = curry(add);
console.log(curriedAdd(1)(2)(3));
console.log(curriedAdd(1, 2)(3));
console.log(curriedAdd(1)(2, 3));
Section 5: Recursion Problems
Q21: Fibonacci (Recursive + Memoized)
// Recursive (exponential)
function fib(n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
// Memoized (O(n))
function fibMemo(n, memo = {}) {
if (n in memo) return memo[n];
if (n <= 1) return n;
memo[n] = fibMemo(n - 1, memo) + fibMemo(n - 2, memo);
return memo[n];
}
console.log(fib(10));
console.log(fibMemo(50));
Q22: Deep Equal
function deepEqual(a, b) {
if (a === b) return true;
if (typeof a !== "object" || typeof b !== "object") return false;
if (a === null || b === null) return false;
const keysA = Object.keys(a);
const keysB = Object.keys(b);
if (keysA.length !== keysB.length) return false;
return keysA.every(key => deepEqual(a[key], b[key]));
}
console.log(deepEqual({ a: 1, b: { c: 2 } }, { a: 1, b: { c: 2 } }));
console.log(deepEqual({ a: 1 }, { a: 2 }));
Q23: Power Function
function power(base, exp) {
if (exp === 0) return 1;
if (exp % 2 === 0) {
const half = power(base, exp / 2);
return half * half;
}
return base * power(base, exp - 1);
}
console.log(power(2, 10)); // 1024
console.log(power(3, 4)); // 81
Section 6: Design Pattern Problems
Q24: Implement EventEmitter
class EventEmitter {
constructor() {
this.events = {};
}
on(event, listener) {
this.events[event] = this.events[event] || [];
this.events[event].push(listener);
return this;
}
emit(event, ...args) {
(this.events[event] || []).forEach(fn => fn(...args));
return this;
}
off(event, listener) {
this.events[event] = (this.events[event] || []).filter(fn => fn !== listener);
return this;
}
once(event, listener) {
const wrapper = (...args) => {
listener(...args);
this.off(event, wrapper);
};
return this.on(event, wrapper);
}
}
const emitter = new EventEmitter();
emitter.on("data", d => console.log("Received:", d));
emitter.emit("data", "Hello!");
emitter.emit("data", "World!");
Received: Hello!
Received: World!
Q25: LRU Cache
class LRUCache {
constructor(capacity) {
this.capacity = capacity;
this.cache = new Map();
}
get(key) {
if (!this.cache.has(key)) return -1;
const val = this.cache.get(key);
this.cache.delete(key);
this.cache.set(key, val); // Move to end (most recent)
return val;
}
put(key, val) {
if (this.cache.has(key)) this.cache.delete(key);
this.cache.set(key, val);
if (this.cache.size > this.capacity) {
this.cache.delete(this.cache.keys().next().value); // Remove oldest
}
}
}
const cache = new LRUCache(3);
cache.put(1, "A");
cache.put(2, "B");
cache.put(3, "C");
console.log(cache.get(1)); // A (1 is now most recent)
cache.put(4, "D"); // evicts 2 (least recently used)
console.log(cache.get(2)); // -1 (evicted)
console.log(cache.get(3)); // C
Common Traps 🪤
| Mistake | Fix |
|---|
Using == instead of === | Always use strict equality |
| Mutating input array | Use [...arr] or arr.slice() to copy |
| Off-by-one in loops | Test with small arrays manually |
| Not handling empty input | Add guard `if (!arr | | !arr.length) return` |
| Forgetting to return in reduce | Always verify your accumulator logic |
Time Complexity Quick Reference
| Solution | Time | Space |
|---|
| Two Sum (hash map) | O(n) | O(n) |
| Flatten (recursive) | O(n) | O(d) — d=depth |
| Deep Clone | O(n) | O(n) |
| Debounce/Throttle | O(1) | O(1) |
| Fibonacci (memo) | O(n) | O(n) |
| LRU Cache get/put | O(1) | O(n) |