Interview Prep: Coding Challenges & Output Questions
This topic directly prepares you for the coding round of JavaScript interviews.
Must-Know Output Questions
// Q1: Event loop order
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');
// Output: A, D, C, B
// Q2: Hoisting trap
var x = 1;
function test() {
console.log(x); // undefined (local var hoisted)
var x = 2;
}
test();
// Q3: Closure in loop
const funcs = [];
for (var i = 0; i < 3; i++) {
funcs.push(() => i);
}
console.log(funcs[0]()); // 3 (not 0!)
// Q4: this in arrow vs regular
const obj = {
x: 1,
getX() { return this.x; },
getXArrow: () => this.x
};
console.log(obj.getX()); // 1
console.log(obj.getXArrow()); // undefined
Common Coding Challenges
// Implement debounce
function debounce(fn, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
// Deep clone
function deepClone(obj) {
return structuredClone(obj); // modern
// or: JSON.parse(JSON.stringify(obj)); // limited
}
// Flatten array
const flat = arr => arr.reduce(
(acc, val) => acc.concat(Array.isArray(val) ? flat(val) : val), []
);
// Promise.all from scratch
function myPromiseAll(promises) {
return new Promise((resolve, reject) => {
const results = [];
let completed = 0;
promises.forEach((p, i) => {
Promise.resolve(p).then(val => {
results[i] = val;
if (++completed === promises.length) resolve(results);
}).catch(reject);
});
});
}