JAVASCRIPT INTERVIEW PREP
Coding Problems
+ Output Questions
0 - 5 Years Experience | Most Asked in Product + MNC
15 20 5
Coding Output React
JavaScript Interview Prep | Final Year & Experienced Developers
Coding Problems
01
Write the code from memory — 15 must-know questions
C1 Remove Duplicates from Array CODING
WRITE THE CODE
// Remove all duplicate values from array
const arr = [1, 2, 2, 3, 4, 4, 5];
// Write 2 methods
ANSWER
// Method 1 - Using Set (fastest)
const unique = [...new Set(arr)];
// Method 2 - Using filter
const unique2 = [Link]((item,i) => [Link](item) === i);
// Output: [1, 2, 3, 4, 5]
WHY
Set automatically removes duplicates
filter keeps item only if its first index matches current index
Set method is cleaner and faster
JavaScript Interview Prep • Coding + Output Questions 2 / 47
C2 Flatten Nested Array CODING
WRITE THE CODE
// Flatten: [1, [2, [3, 4]], 5] → [1, 2, 3, 4, 5]
const arr = [1, [2, [3, 4]], 5];
ANSWER
// Method 1 - Recursive (interview favorite)
function flatten(arr) {
let result = [];
[Link](item => {
if ([Link](item)) result = [Link](flatten(item));
else [Link](item);
});
return result;
}
// Method 2 - Built-in
[Link](Infinity); // → [1, 2, 3, 4, 5]
WHY
If item is array → go deeper (recursive)
If item is not array → push it to result
flat(Infinity) flattens all levels
JavaScript Interview Prep • Coding + Output Questions 3 / 47
C3 Find Missing Number from 1 to N CODING
WRITE THE CODE
// arr = [1,2,4,5,6], n = 6 → find missing
function findMissing(arr, n) { /* write here */ }
ANSWER
function findMissing(arr, n) {
const expected = (n * (n + 1)) / 2; // sum formula
const actual = [Link]((sum, num) => sum + num, 0);
return expected - actual;
}
// findMissing([1,2,4,5,6], 6) → 3
WHY
Sum of 1 to n = n*(n+1)/2
Missing = expected sum - actual sum
Simple math trick — no loop needed
JavaScript Interview Prep • Coding + Output Questions 4 / 47
C4 Rotate Array by K Positions CODING
WRITE THE CODE
// [1,2,3,4,5] rotate by 2 → [4,5,1,2,3]
function rotateArray(arr, k) { /* write here */ }
ANSWER
function rotateArray(arr, k) {
k = k % [Link]; // handle k > length
return [...[Link](-k), ...[Link](0, -k)];
}
// rotateArray([1,2,3,4,5], 2) → [4,5,1,2,3]
WHY
slice(-k) takes last k elements → [4,5]
slice(0,-k) takes remaining → [1,2,3]
Spread and join both parts
JavaScript Interview Prep • Coding + Output Questions 5 / 47
C5 Find Intersection of Two Arrays CODING
WRITE THE CODE
// Find common elements
// arr1=[1,2,3,4], arr2=[2,4,6] → [2,4]
ANSWER
function intersection(arr1, arr2) {
const set1 = new Set(arr1);
return [...new Set([Link](item => [Link](item)))];
}
// → [2, 4]
WHY
Convert arr1 to Set for fast lookup
Filter arr2 — keep only items in set1
Wrap in Set to remove any duplicates
JavaScript Interview Prep • Coding + Output Questions 6 / 47
C6 Reverse a String — 3 Ways CODING
WRITE THE CODE
// Reverse 'hello' → 'olleh'
// Know all 3 methods!
ANSWER
// Method 1 - Built-in (simplest)
[Link]('').reverse().join('');
// Method 2 - Loop
function reverse(str) {
let rev = '';
for (let i = [Link] - 1; i >= 0; i--) rev += str[i];
return rev;
}
// Method 3 - Reduce
[Link]('').reduce((rev, ch) => ch + rev, '');
WHY
Method 1 → split into chars, reverse, join back
Method 2 → loop from end to start
Always explain all 3 in interview
JavaScript Interview Prep • Coding + Output Questions 7 / 47
C7 Palindrome Checker CODING
WRITE THE CODE
// 'racecar' → true, 'hello' → false
function isPalindrome(str) { /* write here */ }
ANSWER
function isPalindrome(str) {
const clean = [Link]().replace(/[^a-z0-9]/g, '');
return clean === [Link]('').reverse().join('');
}
// isPalindrome('A man a plan a canal Panama') → true
WHY
Clean string → lowercase + remove spaces/symbols
Compare string with its reverse
If same → palindrome
JavaScript Interview Prep • Coding + Output Questions 8 / 47
C8 Anagram Checker CODING
WRITE THE CODE
// 'listen' and 'silent' → true (same letters)
function isAnagram(str1, str2) { /* write here */ }
ANSWER
function isAnagram(str1, str2) {
const sort = s => [Link]().split('').sort().join('');
return sort(str1) === sort(str2);
}
// isAnagram('listen', 'silent') → true
WHY
Sort both strings alphabetically
If sorted strings are equal → anagram
Sorting makes comparison easy
JavaScript Interview Prep • Coding + Output Questions 9 / 47
C9 First Non-Repeating Character CODING
WRITE THE CODE
// 'swiss' → 'w' (s repeats, w appears once)
function firstNonRepeating(str) { /* write here */ }
ANSWER
function firstNonRepeating(str) {
const count = {};
for (let ch of str) count[ch] = (count[ch] || 0) + 1;
for (let ch of str) {
if (count[ch] === 1) return ch;
}
return null;
}
// firstNonRepeating('swiss') → 'w'
WHY
Loop 1 → count each character
Loop 2 → return first char with count 1
Two loops, same string = O(n)
JavaScript Interview Prep • Coding + Output Questions 10 / 47
C10 Implement Debounce CODING
WRITE THE CODE
// Delay function call until user stops typing
function debounce(func, delay) { /* write here */ }
ANSWER
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId); // cancel previous
timeoutId = setTimeout(() => {
[Link](this, args);
}, delay);
};
}
// const search = debounce(apiCall, 500);
WHY
Every call cancels the previous timer
Only last call after user stops → runs
Used in search box, autocomplete
JavaScript Interview Prep • Coding + Output Questions 11 / 47
C11 Implement Throttle CODING
WRITE THE CODE
// Allow function max once per time limit
function throttle(func, limit) { /* write here */ }
ANSWER
function throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
[Link](this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
// const scroll = throttle(handler, 1000);
WHY
First call runs immediately
All calls within limit time → ignored
Used in scroll events, button clicks
JavaScript Interview Prep • Coding + Output Questions 12 / 47
C12 Implement map() / filter() / reduce() CODING
WRITE THE CODE
// Implement [Link] from scratch
ANSWER
// myMap
[Link] = function(cb) {
const result = [];
for (let i = 0; i < [Link]; i++) [Link](cb(this[i], i, this));
return result;
};
// myFilter
[Link] = function(cb) {
const result = [];
for (let i = 0; i < [Link]; i++) if (cb(this[i], i, this)) [Link](this[i]);
return result;
};
// myReduce
[Link] = function(cb, init) {
let acc = init !== undefined ? init : this[0];
let start = init !== undefined ? 0 : 1;
for (let i = start; i < [Link]; i++) acc = cb(acc, this[i], i, this);
return acc;
};
WHY
map → loops and returns new transformed array
filter → loops and keeps items where callback is true
reduce → accumulates all values into one
JavaScript Interview Prep • Coding + Output Questions 13 / 47
C13 Implement Curry Function CODING
WRITE THE CODE
// curry(add)(1)(2)(3) should return 6
function curry(fn) { /* write here */ }
ANSWER
function curry(fn) {
return function curried(...args) {
if ([Link] >= [Link]) {
return [Link](this, args); // enough args → call
}
return function(...args2) {
return [Link](this, [Link](args2));
};
};
}
const add = (a,b,c) => a+b+c;
curry(add)(1)(2)(3); // → 6
WHY
If enough arguments → call the function
If not enough → return new function collecting more args
Keeps collecting until [Link] args reached
JavaScript Interview Prep • Coding + Output Questions 14 / 47
C14 FizzBuzz (1 to 100) CODING
WRITE THE CODE
// Print 1-100
// Divisible by 3 → Fizz
// Divisible by 5 → Buzz
// Divisible by both → FizzBuzz
ANSWER
function fizzBuzz() {
for (let i = 1; i <= 100; i++) {
if (i % 15 === 0) [Link]('FizzBuzz');
else if (i % 3 === 0) [Link]('Fizz');
else if (i % 5 === 0) [Link]('Buzz');
else [Link](i);
}
}
WHY
Check 15 FIRST (divisible by both 3 and 5)
If you check 3 or 5 first → FizzBuzz case breaks
Order matters: 15 → 3 → 5 → number
JavaScript Interview Prep • Coding + Output Questions 15 / 47
C15 Fibonacci Series CODING
WRITE THE CODE
// 0,1,1,2,3,5,8,13... each = sum of previous two
// Write both recursive and iterative
ANSWER
// Iterative (preferred - faster)
function fib(n) {
if (n <= 1) return n;
let a = 0, b = 1;
for (let i = 2; i <= n; i++) {
let temp = a + b;
a = b;
b = temp;
}
return b;
}
// Recursive (simple but slow)
function fibR(n) {
if (n <= 1) return n;
return fibR(n-1) + fibR(n-2);
}
WHY
Iterative is O(n) → preferred in interview
Recursive is O(2^n) → slow for large n
Always mention both and their complexity
JavaScript Interview Prep • Coding + Output Questions 16 / 47
Output Questions
02
Predict the output — explain WHY, not just what
O1 Hoisting — var OUTPUT
PREDICT THE OUTPUT
[Link](x); // what prints?
var x = 5;
[Link](x); // what prints?
OUTPUT
→ undefined
→5
WHY
var is hoisted to top but NOT initialized
So first log sees x=undefined (declared not assigned)
After assignment → x becomes 5
JavaScript Interview Prep • Coding + Output Questions 17 / 47
O2 Temporal Dead Zone — let OUTPUT
PREDICT THE OUTPUT
[Link](a); // what happens?
let a = 10;
OUTPUT
→ ReferenceError: Cannot access 'a' before initialization
WHY
let and const are hoisted but NOT accessible before declaration
This gap is called Temporal Dead Zone (TDZ)
var gives undefined, let/const give ReferenceError
JavaScript Interview Prep • Coding + Output Questions 18 / 47
O3 var in Loop + setTimeout OUTPUT
PREDICT THE OUTPUT
for (var i = 0; i < 3; i++) {
setTimeout(() => [Link](i), 0);
}
OUTPUT
→3
→3
→3
WHY
var has function scope, not block scope
All 3 callbacks share the SAME i variable
By the time setTimeout runs, loop ended → i=3
Fix: use let (block-scoped) or IIFE
JavaScript Interview Prep • Coding + Output Questions 19 / 47
O4 let in Loop + setTimeout OUTPUT
PREDICT THE OUTPUT
for (let i = 0; i < 3; i++) {
setTimeout(() => [Link](i), 0);
}
OUTPUT
→0
→1
→2
WHY
let has BLOCK scope
Each loop iteration creates a NEW i variable
So each setTimeout captures its own i
This is why let is preferred over var in loops
JavaScript Interview Prep • Coding + Output Questions 20 / 47
O5 Closure — Counter OUTPUT
PREDICT THE OUTPUT
function outer() {
let count = 0;
return function inner() {
count++;
return count;
}
}
const counter = outer();
[Link](counter());
[Link](counter());
[Link](counter());
OUTPUT
→1
→2
→3
WHY
inner() remembers outer's count variable = CLOSURE
count is NOT reset — it lives in memory
Each call increments the SAME count
This is how React useState works internally
JavaScript Interview Prep • Coding + Output Questions 21 / 47
O6 Closure — Function Array Trap OUTPUT
PREDICT THE OUTPUT
function createFunctions() {
var result = [];
for (var i = 0; i < 3; i++) {
[Link](function() { return i; });
}
return result;
}
var funcs = createFunctions();
[Link](funcs[0]());
[Link](funcs[1]());
OUTPUT
→3
→3
WHY
All functions close over the SAME i (var = shared)
When called, loop is done → i = 3
Fix: use let in for loop → each gets own i
JavaScript Interview Prep • Coding + Output Questions 22 / 47
O7 this — Object Method OUTPUT
PREDICT THE OUTPUT
const obj = {
name: 'John',
greet: function() { [Link]([Link]); }
};
[Link]();
const greet = [Link];
greet();
OUTPUT
→ John
→ undefined (or error in strict mode)
WHY
[Link]() → this = obj → name is 'John'
const greet = [Link] → just a function reference
greet() called alone → this = undefined/window
Fix: use .bind(obj) or arrow function
JavaScript Interview Prep • Coding + Output Questions 23 / 47
O8 this — Arrow Function in Object OUTPUT
PREDICT THE OUTPUT
const person = {
name: 'Alice',
sayName: () => {
[Link]([Link]); // arrow function!
}
};
[Link]();
OUTPUT
→ undefined
WHY
Arrow functions have NO own this
They borrow this from where they were DEFINED
Arrow was defined in global scope → this = window
[Link] is undefined
Fix: use regular function() instead of arrow
JavaScript Interview Prep • Coding + Output Questions 24 / 47
O9 Regular vs Arrow — Same Object OUTPUT
PREDICT THE OUTPUT
const obj = {
a: 1,
b: function() { [Link](this.a); },
c: () => { [Link](this.a); }
};
obj.b();
obj.c();
OUTPUT
→1
→ undefined
WHY
b is regular function → this = obj → a = 1
c is arrow function → this = global → a = undefined
Rule: Never use arrow for object methods
JavaScript Interview Prep • Coding + Output Questions 25 / 47
O10 Event Loop — Micro vs Macro OUTPUT
PREDICT THE OUTPUT
[Link]('Start');
setTimeout(() => [Link]('Timeout'), 0);
[Link]().then(() => [Link]('Promise'));
[Link]('End');
OUTPUT
→ Start
→ End
→ Promise
→ Timeout
WHY
Sync code runs first → Start, End
Promise is MICROTASK → runs before setTimeout
setTimeout is MACROTASK → runs last
Order: Sync → Microtask → Macrotask
JavaScript Interview Prep • Coding + Output Questions 26 / 47
O11 async/await Execution Order OUTPUT
PREDICT THE OUTPUT
async function foo() {
[Link](1);
await [Link](2);
[Link](3);
}
[Link](4);
foo();
[Link](5);
OUTPUT
→4
→1
→2
→5
→3
WHY
4 first → sync code runs before function call
foo() called → 1 logs, then await
await pauses foo() → main thread continues → 5
After microtask queue → 3 resumes
JavaScript Interview Prep • Coding + Output Questions 27 / 47
O12 Promise Constructor Execution OUTPUT
PREDICT THE OUTPUT
const p = new Promise((resolve, reject) => {
[Link](1);
resolve();
[Link](2);
});
[Link](() => [Link](3));
[Link](4);
OUTPUT
→1
→2
→4
→3
WHY
Promise executor runs SYNCHRONOUSLY → 1, 2
resolve() is called but .then() is async (microtask)
Main thread continues → 4
Then microtask runs → 3
JavaScript Interview Prep • Coding + Output Questions 28 / 47
O13 Complex Async Order OUTPUT
PREDICT THE OUTPUT
[Link]('1');
setTimeout(() => [Link]('2'), 0);
[Link]().then(() => [Link]('3'));
[Link]().then(() => setTimeout(() => [Link]('4'), 0));
[Link]().then(() => [Link]('5'));
setTimeout(() => [Link]('6'), 0);
[Link]('7');
OUTPUT
→1→7→3→5→2→6→4
WHY
Sync first: 1, 7
Microtasks: 3, 5 (promise .then callbacks)
setTimeout 4 is added to macro queue during microtask
Macrotasks: 2, 6, 4 (in order they were added)
JavaScript Interview Prep • Coding + Output Questions 29 / 47
O14 [Link] with Reject OUTPUT
PREDICT THE OUTPUT
const p1 = [Link](1);
const p2 = [Link](2);
const p3 = [Link](3);
[Link]([p1, p2, p3])
.then(result => [Link](result))
.catch(err => [Link](err));
OUTPUT
→2
WHY
[Link] FAILS if ANY promise rejects
It rejects immediately with the first rejection value
.then is skipped → .catch runs with value 2
Use [Link] if you want ALL results
JavaScript Interview Prep • Coding + Output Questions 30 / 47
O15 Promise Chain — Error Flow OUTPUT
PREDICT THE OUTPUT
[Link](1)
.then(x => x + 1)
.then(x => { throw new Error('Error!') })
.then(x => [Link](x))
.catch(err => [Link]('Caught'))
.then(x => [Link]('Done'));
OUTPUT
→ Caught
→ Done
WHY
Error thrown in .then → SKIPS all next .then
Goes directly to .catch
After .catch → chain continues → Done
.catch recovers the chain
JavaScript Interview Prep • Coding + Output Questions 31 / 47
O16 Type Coercion Tricks OUTPUT
PREDICT THE OUTPUT
[Link](0.1 + 0.2 === 0.3);
[Link]([] + []);
[Link]([] + {});
[Link]('5' + 3);
[Link]('5' - 3);
[Link](true + false);
OUTPUT
→ false (floating point precision issue)
→ '' (empty string)
→ '[object Object]'
→ '53' (string + number = concatenation)
→2 (string - number = subtraction, converts)
→1 (true=1, false=0)
WHY
+ with string → concatenation
- always converts to number
[] converts to '' (empty string)
{} converts to '[object Object]'
JavaScript Interview Prep • Coding + Output Questions 32 / 47
O17 Hoisting — Function vs Var OUTPUT
PREDICT THE OUTPUT
[Link](foo);
function foo() { return 'Hello'; }
var foo = 'Hi';
[Link](foo);
OUTPUT
→ [Function: foo]
→ 'Hi'
WHY
Functions are fully hoisted (with body)
var is hoisted but undefined
Function hoisting wins over var hoisting
After var foo = 'Hi' → foo becomes string
JavaScript Interview Prep • Coding + Output Questions 33 / 47
O18 Reference Type — Object OUTPUT
PREDICT THE OUTPUT
const obj1 = { a: 1, b: 2 };
const obj2 = obj1;
obj2.a = 3;
[Link](obj1.a);
OUTPUT
→3
WHY
Objects are reference types
obj2 = obj1 → both point to SAME object in memory
Changing obj2.a changes obj1.a too
Fix: use spread { ...obj1 } for shallow copy
JavaScript Interview Prep • Coding + Output Questions 34 / 47
O19 let a = b = 5 Trap OUTPUT
PREDICT THE OUTPUT
let a = b = 5;
(function() {
let a = b = 10;
})();
[Link](a);
[Link](b);
OUTPUT
→5
→ 10
WHY
let a = b = 5 means: b = 5 (global!), let a = 5 (local)
Inside IIFE: b = 10 (updates global b), let a = 10 (local)
Outside: a is still 5, b is now 10
b became global because it was never declared with let/const/var
JavaScript Interview Prep • Coding + Output Questions 35 / 47
O20 nextTick vs setImmediate vs setTimeout (Node)
OUTPUT
PREDICT THE OUTPUT
setTimeout(() => [Link]('1'), 0);
setImmediate(() => [Link]('2'));
[Link](() => [Link]('3'));
[Link]('4');
OUTPUT
→4
→3
→ 1 or 2 (order may vary)
→ 2 or 1
WHY
Sync runs first → 4
[Link] → runs immediately after current sync
setTimeout and setImmediate → next event loop cycles
nextTick: highest priority of all async callbacks
JavaScript Interview Prep • Coding + Output Questions 36 / 47
React Output Questions
03
Common React behavior traps — asked in every React round
R1 useState — Stale Closure OUTPUT
PREDICT THE OUTPUT
function Counter() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
};
return <button onClick={increment}>{count}</button>;
}
// Click button — what value shows?
OUTPUT
→ count becomes 1 (NOT 3)
WHY
All 3 setCount use the SAME stale count value (0)
count + 1 = 1, three times
Fix: use functional update → setCount(prev => prev + 1)
That way each update gets the latest value → becomes 3
JavaScript Interview Prep • Coding + Output Questions 37 / 47
R2 useEffect — Infinite Loop OUTPUT
PREDICT THE OUTPUT
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
setCount(count + 1); // inside effect!
}, [count]); // count in dependency
return <div>{count}</div>;
}
OUTPUT
→ Infinite loop! App crashes
WHY
setCount → count changes → triggers useEffect again
useEffect runs → setCount again → infinite cycle
Fix: remove count from dependency array []
Or use setCount(prev => prev + 1) with [] dependency
JavaScript Interview Prep • Coding + Output Questions 38 / 47
R3 useEffect — Console Order OUTPUT
PREDICT THE OUTPUT
function App() {
[Link]('1');
useEffect(() => { [Link]('2'); }, []);
useEffect(() => { [Link]('3'); });
[Link]('4');
return <div>App</div>;
}
OUTPUT
→1
→4
→2
→3
WHY
Render phase runs first: 1, 4
After paint → useEffects run in ORDER
[] runs once on mount → 2
No dependency → runs every render → 3
JavaScript Interview Prep • Coding + Output Questions 39 / 47
R4 Mutating State — No Re-render OUTPUT
PREDICT THE OUTPUT
function App() {
const [items, setItems] = useState([1,2,3]);
const addItem = () => {
[Link](4); // mutate directly!
setItems(items); // same reference
};
return <button onClick={addItem}>Add</button>;
}
OUTPUT
→ UI does NOT update (no re-render)
WHY
[Link] mutates the ORIGINAL array
setItems(items) → same reference → React sees no change
React compares references, not deep values
Fix: setItems([...items, 4]) → new array reference
JavaScript Interview Prep • Coding + Output Questions 40 / 47
R5 Child Re-renders — Fix with memo OUTPUT
PREDICT THE OUTPUT
function Child({ onClick }) {
[Link]('Child rendered');
return <button onClick={onClick}>Click</button>;
}
function Parent() {
const [count, setCount] = useState(0);
const handleClick = () => setCount(count + 1);
return <div><Child onClick={handleClick} /></div>;
}
// Every Parent render → Child also renders. Why?
OUTPUT
→ Child renders on every Parent render
WHY
handleClick is created NEW on every render
New function = new reference = Child thinks prop changed
Fix 1: wrap Child in [Link](Child)
Fix 2: wrap handleClick in useCallback(() => ..., [])
Both together = Child only renders when truly needed
JavaScript Interview Prep • Coding + Output Questions 41 / 47