Chapter 77
Advanced
25 min read
Interview Prep
JavaScript Interview Prep — Top 50 Questions
These are the real questions asked in frontend, full-stack, and MERN stack interviews at top companies. Master every concept here and walk into any JS interview with confidence.
Core JavaScript (Q1 – Q10)
Q1
What are the data types in JavaScript?
Core
JavaScript has 8 data types: 7 primitive types and 1 non-primitive
(object).
Primitives — stored by value, immutable:
Non-primitive — stored by reference, mutable:
Primitives — stored by value, immutable:
string, number, bigint, boolean, undefined, null, symbol.Non-primitive — stored by reference, mutable:
object (includes arrays, functions, dates, etc.).
JavaScript
typeof "hello" // "string"
typeof 42 // "number"
typeof 9007199254740991n // "bigint"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" ← famous JS quirk!
typeof Symbol() // "symbol"
typeof {} // "object"
typeof [] // "object"
typeof function(){} // "function"
Q2
What is the difference between
Core
var, let, and
const?
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Hoisted? | Yes (undefined) | Yes (TDZ) | Yes (TDZ) |
| Re-declare? |
|
|
|
| Re-assign? |
|
|
|
| Global property? | Yes | No | No |
TDZ (Temporal Dead Zone) — accessing
let/const
before declaration throws a ReferenceError. Use
const by default, let when re-assignment is needed, and avoid var
in modern code.
Q3
What is hoisting in JavaScript?
Core
Hoisting is JavaScript's behaviour of moving variable and function
declarations to the top of their scope before execution — only the declaration is
moved, not the initialisation.
JavaScript
console.log(a); // undefined (var is hoisted)
var a = 5;
console.log(b); // ReferenceError (let TDZ)
let b = 10;
// Function declarations are fully hoisted:
greet(); // "Hello!" — works!
function greet() { console.log("Hello!"); }
// Function expressions are NOT hoisted:
sayHi(); // TypeError: sayHi is not a function
var sayHi = function() { console.log("Hi!"); };
Q4
What is the difference between
Core
== and ===?
== (Abstract Equality) —
compares values after performing type coercion. JavaScript converts both operands to
the same type before comparing.=== (Strict Equality) —
compares both value AND type, no coercion. Always prefer === to avoid subtle bugs.
JavaScript
0 == "" // true (both coerced to 0)
0 === "" // false (number vs string)
null == undefined // true
null === undefined // false
"1" == 1 // true (coercion)
"1" === 1 // false
Q5
What is a closure in JavaScript?
Core
A closure is a function that retains access to its lexical
scope even after the outer function has finished executing. Closures
are created every time a function is created. They enable data privacy, partial
application, and factory functions.
JavaScript
function makeCounter() {
let count = 0; // private variable
return {
increment: () => ++count,
decrement: () => --count,
getCount: () => count,
};
}
const counter = makeCounter();
counter.increment(); // 1
counter.increment(); // 2
counter.getCount(); // 2 — count is private!
Q6
What is the difference between
Core
null and undefined?undefined — a variable declared
but not yet assigned a value. JS sets it automatically.null — an intentional
assignment representing "no value" or "empty." It must be explicitly set by the
developer.Key quirk:
typeof null === "object" — a
well-known JS bug that will never be fixed for backward compatibility.
Q7
What is type coercion in JavaScript?
Core
Type coercion is the automatic conversion of one data type to
another. Implicit coercion happens automatically; explicit
coercion uses functions like
Number(),
String(), Boolean().
JavaScript
// Implicit coercion
"5" + 3 // "53" (number → string)
"5" - 3 // 2 (string → number)
true + 1 // 2 (boolean → number)
[] + [] // "" (array → string)
// Falsy values: false, 0, "", null, undefined, NaN
if ("") console.log("runs?"); // No — empty string is falsy
if ("0") console.log("runs?"); // Yes — non-empty string is truthy
Q8
What is an IIFE and why is it used?
Core
An IIFE (Immediately Invoked Function Expression) is a function
that runs immediately after it is defined. It creates a private scope, avoiding
polluting the global namespace — widely used before ES6 modules.
JavaScript
(function () {
const secret = "I am private";
console.log(secret); // "I am private"
})();
// Arrow IIFE (ES6)
(() => {
console.log("Arrow IIFE runs too!");
})();
Q9
What is event bubbling and event capturing?
Core
When an event fires on a DOM element, it propagates in two phases:
Capturing (top-down) — the event travels from
Bubbling (bottom-up) — the event travels from the target element back up to
Use
Capturing (top-down) — the event travels from
window down to the target element.Bubbling (bottom-up) — the event travels from the target element back up to
window. Default behavior is
bubbling.Use
e.stopPropagation() to stop bubbling. Use
the third argument of addEventListener(event, fn, true) for capturing
phase.
Q10
What is the difference between
Core
deep copy and shallow copy?
Shallow copy — copies only the top-level properties. Nested objects
still share the same reference.
Deep copy — recursively copies all nested properties. Completely independent from the original.
Deep copy — recursively copies all nested properties. Completely independent from the original.
JavaScript
const original = { a: 1, b: { c: 2 } };
// Shallow copy
const shallow = { ...original };
shallow.b.c = 99;
console.log(original.b.c); // 99 — same reference!
// Deep copy (modern)
const deep = structuredClone(original);
deep.b.c = 100;
console.log(original.b.c); // 99 — untouched ✅
// Alternative: JSON.parse(JSON.stringify(obj)) ← loses functions/dates
Advertisement
Functions & Scope (Q11 – Q20)
Q11
What are arrow functions? How do they differ from regular
functions?
Functions
Arrow functions (
1. No own
2. No
3. Cannot be used as constructors (no
4. No
5. Implicit return when body is a single expression without braces.
=>) are a concise function
syntax introduced in ES6. Key differences from regular functions:1. No own
this — they inherit
this from the enclosing lexical scope (no
binding).2. No
arguments object — use
rest params instead.3. Cannot be used as constructors (no
new).4. No
prototype property.5. Implicit return when body is a single expression without braces.
JavaScript
const timer = {
seconds: 0,
startRegular: function() {
setInterval(function() {
console.log(this.seconds++); // ❌ this = window
}, 1000);
},
startArrow: function() {
setInterval(() => {
console.log(this.seconds++); // ✅ this = timer
}, 1000);
}
};
Q12
Explain
Functions
call(), apply(), and bind().
All three allow you to explicitly set the value of
this for a function. The difference is in how
arguments are passed and when the function executes.
JavaScript
function greet(greeting, punct) {
console.log(`${greeting}, ${this.name}${punct}`);
}
const user = { name: "Arjun" };
// call — args as comma-separated list, executes immediately
greet.call(user, "Hello", "!"); // "Hello, Arjun!"
// apply — args as an array, executes immediately
greet.apply(user, ["Hi", "."]); // "Hi, Arjun."
// bind — returns a NEW function with this bound (does NOT execute)
const boundGreet = greet.bind(user, "Hey");
boundGreet("?"); // "Hey, Arjun?"
Q13
What is the
Functions
this keyword?
How is its value determined?this refers to the object that is currently
executing the function. Its value is determined by how a function is
called, not where it is defined (except for arrow functions which use
lexical this).
Global context
this === window
(browser) or global (Node.js). In strict
mode, this === undefined.Method call
obj.method() →
this is obj.
Constructor call
new Fn() →
this is the newly created object.
Explicit binding
call / apply / bind → this is the first argument.
Q14
What is currying in JavaScript?
Functions
Currying is the technique of transforming a function that takes
multiple arguments into a sequence of functions that each take a single argument. It
enables partial application and function reuse.
JavaScript
// Normal function
function add(a, b) { return a + b; }
// Curried version
const curriedAdd = a => b => a + b;
const add5 = curriedAdd(5); // partial application
add5(3); // 8
add5(10); // 15
Q15
What are higher-order functions?
Functions
A higher-order function is a function that either (1) takes one or
more functions as arguments, or (2) returns a function as its result. Examples:
map(), filter(), reduce(), forEach(), setTimeout(), bind().
JavaScript
[1,2,3].map(x => x * 2); // [2, 4, 6]
[1,2,3].filter(x => x > 1); // [2, 3]
[1,2,3].reduce((acc,x) => acc+x, 0); // 6
// Returns a function — HOF
const multiplier = n => x => x * n;
const double = multiplier(2);
double(5); // 10
Q16
What is memoization?
Functions
Memoization is an optimisation technique that caches the results of
expensive function calls. When the same inputs occur again, the cached result is
returned instead of recomputing — great for recursive or pure functions.
JavaScript
function memoize(fn) {
const cache = new Map();
return function(...args) {
const key = JSON.stringify(args);
if (cache.has(key)) return cache.get(key);
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}
const slowSquare = n => n * n;
const fastSquare = memoize(slowSquare);
fastSquare(10); // computed
fastSquare(10); // returned from cache ⚡
Q17
What is the scope chain in JavaScript?
Functions
The scope chain is the mechanism JavaScript uses to resolve
variable references. When a variable is accessed inside a function, JS looks in the
current scope, then in each outer (parent) scope, all the way up to the global
scope. If not found anywhere, a
ReferenceError
is thrown.
Q18
What are generator functions?
Functions
Generators are functions that can be paused and resumed. Defined
with
function*, they use yield to produce a series of values lazily — ideal
for infinite sequences and async control flow.
JavaScript
function* counter() {
let i = 0;
while (true) yield i++;
}
const gen = counter();
gen.next().value; // 0
gen.next().value; // 1
gen.next().value; // 2 — infinite, but lazy!
Q19
What is the difference between function declaration and
function expression?
Functions
Function declaration — uses the
Function expression — assigns an anonymous (or named) function to a variable. Not hoisted — calling before assignment throws a
function keyword as a statement. It is fully
hoisted — can be called before its definition in code.Function expression — assigns an anonymous (or named) function to a variable. Not hoisted — calling before assignment throws a
TypeError.
Q20
What is a pure function?
Functions
A pure function is a function that: (1) always returns the same
output for the same input, and (2) has no side effects (doesn't modify external
state, make API calls, etc.). Pure functions are predictable, testable, and the
foundation of functional programming.
JavaScript
// ✅ Pure — same input → same output, no side effects
const add = (a, b) => a + b;
// ❌ Impure — modifies external state
let total = 0;
const addToTotal = n => { total += n; return total; };
Arrays & Objects (Q21 – Q30)
Q21
What is the difference between
Arrays
map(), filter(), and reduce()?| Method | Returns | Use case |
|---|---|---|
| map() | New array (same length) | Transform each element |
| filter() | New array (subset) | Remove unwanted items |
| reduce() | Single value (any type) | Accumulate / fold array |
JavaScript
const nums = [1,2,3,4,5];
nums.map(n => n * 2); // [2,4,6,8,10]
nums.filter(n => n % 2 === 0); // [2,4]
nums.reduce((acc, n) => acc + n, 0);// 15
Q22
What is destructuring in JavaScript?
Arrays
Destructuring is a syntax that allows unpacking values from arrays
or properties from objects into distinct variables in a single, concise statement.
JavaScript
// Array destructuring
const [a, b, ...rest] = [1, 2, 3, 4];
// a=1, b=2, rest=[3,4]
// Object destructuring
const { name, age = 18, address: { city } } = {
name: "Arjun", age: 25, address: { city: "Vadodara" }
};
// name="Arjun", age=25, city="Vadodara"
// Swap variables
let x = 1, y = 2;
[x, y] = [y, x]; // x=2, y=1
Q23
What is the spread operator and rest parameters?
Arrays
Both use the
Spread — expands an iterable into individual elements (at call site).
Rest — collects multiple elements into an array (at definition site).
... syntax but in opposite
contexts.Spread — expands an iterable into individual elements (at call site).
Rest — collects multiple elements into an array (at definition site).
JavaScript
// Spread — expands
const arr1 = [1, 2];
const arr2 = [3, ...arr1, 4]; // [3,1,2,4]
const obj1 = { a: 1 };
const obj2 = { ...obj1, b: 2 }; // {a:1, b:2}
// Rest — collects
function sum(...nums) {
return nums.reduce((acc, n) => acc + n, 0);
}
sum(1, 2, 3, 4); // 10
Q24
How does the prototype chain work?
Objects
Every JavaScript object has an internal
[[Prototype]] property (accessible via __proto__ or Object.getPrototypeOf()). When you access a
property, JS first checks the object itself, then walks up the prototype chain until
it finds the property or reaches null. This is
prototype-based inheritance.
JavaScript
const animal = { breathes: true };
const dog = Object.create(animal);
dog.name = "Rex";
dog.breathes; // true — found on prototype
dog.name; // "Rex" — found on dog itself
// Chain: dog → animal → Object.prototype → null
Q25
What is optional chaining (
Objects
?.) and nullish coalescing (??)?
Optional chaining
Nullish coalescing
?. — safely
accesses nested properties without throwing if an intermediate value is null or undefined.Nullish coalescing
?? — returns
the right-hand side only when the left-hand side is null or undefined (unlike || which also catches falsy values like 0 or "").
JavaScript
const user = { profile: null };
user?.profile?.name; // undefined (no error)
user?.profile?.name ?? "Guest"; // "Guest"
const count = 0;
count || "default"; // "default" (0 is falsy — bad!)
count ?? "default"; // 0 (0 is not null/undefined — correct!)
Q26
What are
Objects
Map and Set? How do they differ from objects and arrays?
Map — like an object but any value (including objects) can be a
key; maintains insertion order; has a
Set — like an array but stores only unique values; useful for deduplication.
.size
property.Set — like an array but stores only unique values; useful for deduplication.
JavaScript
// Map
const map = new Map();
map.set({ id: 1 }, "object as key");
map.size; // 1
// Set — deduplication trick
const unique = [...new Set([1,2,2,3,3])]; // [1,2,3]
Q27
What does
Objects
Object.freeze()
do?Object.freeze() prevents new properties from
being added, existing properties from being modified or deleted. The freeze is
shallow — nested objects are still mutable.
JavaScript
const config = Object.freeze({ port: 3000, db: { host: "localhost" } });
config.port = 8080; // ❌ silently ignored (error in strict mode)
config.db.host = "prod"; // ✅ works! (shallow freeze)
Q28
What are
Objects
Object.keys(),
Object.values(), and Object.entries()?
All three return arrays from an object's own enumerable properties only (not
prototype chain). They're essential for iterating objects.
JavaScript
const obj = { a: 1, b: 2, c: 3 };
Object.keys(obj); // ["a", "b", "c"]
Object.values(obj); // [1, 2, 3]
Object.entries(obj); // [["a",1], ["b",2], ["c",3]]
// Build object from entries
const doubled = Object.fromEntries(
Object.entries(obj).map(([k, v]) => [k, v * 2])
); // {a:2, b:4, c:6}
Q29
What is
Arrays
Array.flat() and
Array.flatMap()?
flat(depth) — flattens nested arrays to the
specified depth (default: 1). Use Infinity for
fully nested arrays.flatMap(fn) — equivalent to calling .map(fn).flat(1). Great for expanding items.
JavaScript
[1, [2, [3]]].flat(); // [1, 2, [3]]
[1, [2, [3]]].flat(Infinity); // [1, 2, 3]
["hello world", "foo bar"]
.flatMap(s => s.split(" "));
// ["hello", "world", "foo", "bar"]
Q30
What are
Objects
WeakMap and WeakSet?
WeakMap — like Map, but keys must be objects and are held weakly.
If a key object is garbage-collected, the entry is automatically removed. Not
iterable — no
WeakSet — like Set, but only holds objects and weakly. Use cases: private data storage, tracking DOM nodes without memory leaks.
.size or loops.WeakSet — like Set, but only holds objects and weakly. Use cases: private data storage, tracking DOM nodes without memory leaks.
Advertisement
Async JavaScript (Q31 – Q40)
Q31
Explain the JavaScript Event Loop.
Async
JavaScript is single-threaded but non-blocking. The event loop is
the mechanism that allows asynchronous operations:
Call Stack
Executes synchronous code line-by-line. LIFO (last
in, first out).
Web APIs
Browser handles timers, fetch, events — off the
main thread.
Microtask Queue
Holds resolved Promises. Always runs
before the macrotask queue.
Macrotask Queue
Holds setTimeout/setInterval callbacks. Runs after
microtasks are empty.
JavaScript — Event Loop order
console.log("1 — sync");
setTimeout(() => console.log("4 — macro"), 0);
Promise.resolve().then(() => console.log("3 — micro"));
console.log("2 — sync");
// Output: 1 — sync, 2 — sync, 3 — micro, 4 — macro
Q32
What are Promises? What are their states?
Async
A Promise is an object representing the eventual completion or
failure of an asynchronous operation. It exists in one of three states:
pending
Initial state. Neither fulfilled nor rejected.
fulfilled
Operation succeeded.
.then() callback runs.rejected
Operation failed.
.catch() callback runs.
JavaScript
const p = new Promise((resolve, reject) => {
setTimeout(() => resolve("✅ Done!"), 1000);
});
p.then(result => console.log(result))
.catch(err => console.error(err))
.finally(() => console.log("Always runs"));
Q33
How does
Async
async/await work?
async/await is syntactic sugar over Promises. An
async function always returns a Promise. await pauses execution of the async function until
the Promise settles — without blocking the main thread.
JavaScript
async function fetchUser(id) {
try {
const res = await fetch(`/api/users/${id}`);
const data = await res.json();
return data;
} catch (err) {
console.error("Fetch failed:", err);
}
}
// Run in parallel — don't await serially!
const [user, posts] = await Promise.all([
fetchUser(1),
fetch("/api/posts").then(r => r.json())
]);
Q34
What is the difference between
Async
Promise.all(), Promise.allSettled(), Promise.race(), and Promise.any()?| Method | Resolves when | Rejects when |
|---|---|---|
| Promise.all() | ALL resolve | ANY rejects (fail-fast) |
| Promise.allSettled() | ALL settle (resolve or reject) | Never rejects |
| Promise.race() | FIRST settles (win or lose) | If first rejects |
| Promise.any() | FIRST resolves | ALL reject (AggregateError) |
Q35
What is callback hell and how do you avoid it?
Async
Callback hell (also called the "pyramid of doom") is deeply nested
callbacks that make code hard to read, debug, and maintain. Solutions: use
Promises (chain
.then()), or
async/await for flat, readable async code.
JavaScript
// ❌ Callback hell
getUser(id, (user) => {
getPosts(user, (posts) => {
getComments(posts[0], (comments) => {
// ... deeper and deeper
});
});
});
// ✅ async/await — flat & readable
async function loadData(id) {
const user = await getUser(id);
const posts = await getPosts(user);
const comments = await getComments(posts[0]);
return comments;
}
Q36
What is the Fetch API? How does it differ from XMLHttpRequest?
Async
fetch() is a modern, Promise-based API for
making HTTP requests. It is cleaner and supports async/await naturally.Key difference from XHR:
fetch() does
not reject on HTTP error codes (like 404/500) — only on network
failure. You must check response.ok manually.
JavaScript
async function getData(url) {
const res = await fetch(url);
if (!res.ok) {
throw new Error(`HTTP error: ${res.status}`);
}
return res.json(); // returns another Promise
}
getData("https://api.example.com/data")
.then(data => console.log(data))
.catch(err => console.error(err));
Q37
What is the difference between
Async
setTimeout and setInterval?setTimeout(fn, ms) — runs fn once after at least ms milliseconds.setInterval(fn, ms) — runs
fn repeatedly every ms milliseconds until cleared with clearInterval(id).For precise repeated execution, prefer recursive setTimeout over setInterval — it guarantees the delay is between executions, not between starts.
Q38
What is
Async
try/catch/finally?
How does it work with async/await?try runs code that might throw. catch(err) handles the error. finally always runs, whether or not an error
occurred — used for cleanup (e.g., hiding a loading spinner). With async/await, wrap awaited calls in try/catch to handle rejected Promises.
JavaScript
async function loadData() {
setLoading(true);
try {
const data = await fetch("/api/data").then(r => r.json());
render(data);
} catch (err) {
showError(err.message);
} finally {
setLoading(false); // always hides spinner
}
}
Q39
What is debouncing and throttling?
Async
Both are techniques to control how often a function is called in rapid-fire events
like typing or scrolling.
Debounce — waits until the event stops firing for X ms, then calls the function once. (Search input: fire API only after user stops typing.)
Throttle — calls the function at most once per X ms interval, regardless of how often the event fires. (Scroll handler: max 1 call per 100ms.)
Debounce — waits until the event stops firing for X ms, then calls the function once. (Search input: fire API only after user stops typing.)
Throttle — calls the function at most once per X ms interval, regardless of how often the event fires. (Scroll handler: max 1 call per 100ms.)
JavaScript — debounce
function debounce(fn, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
const onSearch = debounce(query => fetchResults(query), 300);
input.addEventListener("input", e => onSearch(e.target.value));
Q40
What is the difference between microtasks and macrotasks?
Async
Microtasks — high priority queue processed after every task and
before any macrotask. Sources:
Macrotasks — lower priority; one processed per event loop tick. Sources:
After each macrotask, all queued microtasks run before the next macrotask.
Promise.then,
queueMicrotask(), MutationObserver.Macrotasks — lower priority; one processed per event loop tick. Sources:
setTimeout, setInterval, I/O, UI rendering.After each macrotask, all queued microtasks run before the next macrotask.
Advertisement
Advanced Topics (Q41 – Q50)
Q41
What is a
Advanced
Proxy in
JavaScript?
A Proxy wraps an object and intercepts fundamental operations like
property access, assignment, and function calls via traps. It's
used for validation, logging, reactivity (Vue 3 uses Proxy internally), and
virtualisation.
JavaScript
const user = { name: "Arjun", age: 25 };
const validatedUser = new Proxy(user, {
set(target, prop, value) {
if (prop === "age" && typeof value !== "number")
throw new TypeError("Age must be a number");
target[prop] = value;
return true;
}
});
validatedUser.age = 30; // ✅ ok
validatedUser.age = "old"; // ❌ throws TypeError
Q42
What is
Advanced
Symbol and when
would you use it?Symbol creates a unique, immutable primitive
value. Every symbol is guaranteed to be different from every other symbol — even if
they have the same description. Use cases: unique object keys (no accidental key
collision), well-known symbols like Symbol.iterator.
JavaScript
const id = Symbol("id");
const id2 = Symbol("id");
id === id2; // false — always unique!
const user = { [id]: 123, name: "Arjun" };
user[id]; // 123 — only accessible via symbol
// Won't show in Object.keys() or JSON.stringify()
Q43
What is the difference between
Advanced
localStorage and sessionStorage?| Feature | localStorage | sessionStorage |
|---|---|---|
| Persistence | Until manually cleared | Until tab is closed |
| Scope | All tabs of same origin | Current tab only |
| Storage limit | ~5–10 MB | ~5 MB |
| Sent with requests? | No | No |
| API | Same as sessionStorage | Same as localStorage |
Q44
What is the difference between ES Modules and CommonJS?
Advanced
CommonJS (CJS) — Node.js default. Synchronous, dynamic imports with
ES Modules (ESM) — Modern standard. Static
require()/module.exports. Loaded at runtime.ES Modules (ESM) — Modern standard. Static
import/export
statements. Asynchronous. Supports tree-shaking. Works natively in browsers.
JavaScript
// CommonJS
const math = require("./math");
module.exports = { add };
// ES Modules
import { add } from "./math.js";
export const multiply = (a, b) => a * b;
export default function main() {}
// Dynamic import (lazy-loading)
const { heavy } = await import("./heavy.js");
Q45
What is the difference between
Advanced
for...in and for...of?for...in — iterates over
enumerable property keys of an object (and its prototype chain). Use on
objects, not arrays.for...of — iterates over
values of any iterable (arrays, strings, Maps, Sets, generators). Cannot
iterate plain objects unless you implement Symbol.iterator.
JavaScript
const obj = { a: 1, b: 2 };
for (const key in obj) console.log(key); // "a", "b"
const arr = [10, 20, 30];
for (const val of arr) console.log(val); // 10, 20, 30
for (const char of "JS") console.log(char); // "J", "S"
Q46
What is event delegation?
Advanced
Event delegation is a pattern where a single event listener is
placed on a parent element to handle events from multiple child elements using event
bubbling. This is more efficient than attaching individual listeners, especially for
dynamic content.
JavaScript
// One listener handles ALL list item clicks
document.querySelector("#list")
.addEventListener("click", (e) => {
if (e.target.matches("li")) {
console.log("Clicked:", e.target.textContent);
}
});
Q47
What is tree shaking?
Advanced
Tree shaking is a build-time optimisation (performed by bundlers
like Webpack and Vite) that removes unused code (dead code) from the final
JavaScript bundle. It works because ES Module
import/export
is statically analysable — the bundler knows at build time exactly which exports are
used.
Q48
What are common JavaScript design patterns?
Advanced
Singleton
Ensures a class has only one instance. Used for
global stores, DB connections.
Observer
Objects subscribe to events; publisher notifies all
subscribers. Basis of EventEmitter, Redux.
Factory
A function/class that creates objects without
specifying the exact class. Flexible object creation.
Module
Encapsulates private state using closures or ES
Modules. IIFE was the pre-ES6 form.
Q49
What is TypeScript and why should you use it?
Advanced
TypeScript is a statically-typed superset of JavaScript developed
by Microsoft. It adds optional type annotations, interfaces, and type inference.
TypeScript compiles to plain JavaScript.
Benefits: catch bugs at compile time, better IDE autocomplete/IntelliSense, self-documenting code, safer refactoring, essential for large codebases and team collaboration.
Benefits: catch bugs at compile time, better IDE autocomplete/IntelliSense, self-documenting code, safer refactoring, essential for large codebases and team collaboration.
TypeScript
interface User {
id: number;
name: string;
role: "admin" | "user";
}
function greetUser(user: User): string {
return `Hello, ${user.name} (${user.role})`;
}
const me: User = { id: 1, name: "Arjun", role: "admin" };
greetUser(me); // ✅ type-safe!
Q50
What is the Virtual DOM and how does React use it?
Advanced
The Virtual DOM is an in-memory JavaScript representation of the
real DOM tree. Frameworks like React maintain this lightweight copy and use a
diffing algorithm to compare the new virtual DOM with the previous
one (reconciliation). Only the minimal set of real DOM changes are applied — making
updates much faster than re-rendering the entire page.
Pro Interview Tips
These habits separate good candidates from great ones:
typeof null, coercion, hoisting, and event loop are
always tested. These are high-signal questions.
Map over an object, or
const over let.
Demonstrate judgment.
Try It — Practice in the Live Editor
Live Editor — Interview Practice
✎ Editor
👁 Preview
Which of the following correctly explains why Promise.allSettled() is preferred over Promise.all() in some cases?
- Core JS: Know your 8 data types, var/let/const differences, hoisting,
closures, type coercion, and the infamous
typeof null === "object". - Functions: Arrow functions don't have their own
this.call/applyexecute immediately;bindreturns a new function. Closures power data privacy. - Arrays & Objects: Prefer
structuredClone()for deep copies. Map/Set for keyed data. Spread creates shallow copies only. - Async: The event loop processes microtasks (Promises) before macrotasks
(setTimeout).
async/awaitis just Promise syntactic sugar. Debounce and throttle control event frequency. - Advanced: Proxy intercepts object operations. Symbol creates guaranteed unique keys. ES Modules are statically analysable, enabling tree shaking. TypeScript adds static types to JS.
- Always think out loud, clarify edge cases, and mention time/space complexity — these habits set you apart in any technical interview.
Rate Us on Google
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and
encourages us to keep creating quality content.
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.