var: old style. Scoped to the whole function, hoisted as undefined, can be redeclared. Leaks out of if and for blocks.
let: scoped to the nearest block{ }, can be reassigned.
const: block-scoped, can’t be reassigned, but objects inside can still change.
if (true) { var a = 1; let b = 2; }
console.log(a); // 1
console.log(b); // ReferenceError
const user = { name: 'Ali' };
user.name = 'Sara'; // allowed
user = {}; // TypeError
Say it like this in the interview
“var is function-scoped and hoisted with an initial undefined. let and const are block-scoped and sit in the temporal dead zone until declared. const prevents reassignment, not mutation. I default to const, use let when I reassign, and never var.”
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
In simple words
var creates onei shared by all three callbacks. The callbacks run later, after the loop finished, when i is already 3. With let, each loop round gets its own fresh i, so it prints 0 1 2.
Say it like this in the interview
“3 3 3. var is function-scoped, so all three closures share one variable, which is 3 by the time the timeouts run. Changing to let creates a new binding per iteration and prints 0 1 2.”
Hoisting: before running, JS moves declarations to the top. A function declaration is lifted completely, so you can call it early. A const is lifted but locked (temporal dead zone) until its line runs, so calling sayHi early throws.
Say it like this in the interview
“hello, then a ReferenceError. Function declarations are hoisted with their body. const bindings are hoisted but uninitialised until their declaration executes.”
A closure is a function that remembers the variables from where it was created, even after that outer function has finished. Like a backpack the function carries around.
function makeCounter() {
let count = 0; // private
return () => ++count;
}
const next = makeCounter();
next(); // 1
next(); // 2 (count was remembered)
Say it like this in the interview
“A closure is a function bundled with references to its outer lexical scope. It’s how we get private state, like this counter, and it’s everywhere: event handlers, callbacks, React hooks, debounce functions. The risk is memory: a closure keeps its captured variables alive.”
Debounce = “wait until they stop”. Every keystroke cancels the previous timer and starts a new one. The function runs only when the user pauses for 300ms, so a search box sends one request, not twenty. Throttle is different: run at most once every X ms, used for scroll events.
function debounce(fn, wait = 300) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), wait);
};
}
searchInput.addEventListener('input', debounce(e => search(e.target.value), 300));
Say it like this in the interview
“A closure keeps the timer; every call clears it and sets a new one, so fn runs only after wait ms of silence. I use apply(this, args) to keep context and arguments. Debounce suits search input; throttle suits scroll or resize.”
For normal functions, this is whoever is left of the dot when you call it. user.regular() has user before the dot. fn() has nothing before the dot, so this is undefined in modules/strict mode. Arrow functions don’t have their own this; they borrow it from where they were written (here, module top level, where it’s undefined).
Say it like this in the interview
“Ali, undefined, undefined. A regular function’s this depends on how it’s called; detaching it loses the object. Arrow functions capture this lexically, so they shouldn’t be used as object methods. To keep this, use bind or call it as a method.”
All three let you choose what this is. call and apply run the function now (arguments as a list or an array); bind gives you a new function to run later.
Say it like this in the interview
“fn.call(obj, a, b) and fn.apply(obj, [a, b]) invoke immediately with this = obj. fn.bind(obj, a) returns a new function with this and optional arguments fixed, commonly used for event handlers and callbacks.”
Throttle means “at most once every X milliseconds”, no matter how often it’s called. Useful for scroll and resize events.
function throttle(fn, wait = 200) {
let last = 0;
return function (...args) {
const now = Date.now();
if (now - last >= wait) {
last = now;
fn.apply(this, args);
}
};
}
Say it like this in the interview
“I track the last run time; calls within the window are ignored. A more complete version also schedules a trailing call so the final event isn’t lost.”
Currying turns add(1, 2, 3) into add(1)(2)(3): each call takes some arguments and waits for the rest.
function curry(fn) {
return function curried(...args) {
return args.length >= fn.length
? fn.apply(this, args)
: (...more) => curried.apply(this, [...args, ...more]);
};
}
const add3 = curry((a, b, c) => a + b + c);
add3(1)(2)(3); // 6
Say it like this in the interview
“A curried function collects arguments until it has as many as the original’s length, then calls it. Useful for creating specialised functions like const addTax = multiply(1.17).”
JS has one worker. It first finishes all normal code (A, D). Then it empties the VIP queue (microtasks: promises) → C. Only then does it take from the normal queue (macrotasks: timers) → B. A 0ms timer means “as soon as possible”, not “now”.
Say it like this in the interview
“A, D, C, B. Synchronous code runs first. Then the microtask queue, which holds promise callbacks, is fully drained, before the event loop takes the next macrotask like a setTimeout callback.”
function getUser() {
fetch('/api/user').then(res => res.json());
}
const user = getUser();
console.log(user);
In simple words
Two problems. getUser doesn’t return anything. And even if it returned the promise, the data isn’t there yet: a promise is a receipt for a future value, so you must await it or use .then.
Say it like this in the interview
“getUser doesn’t return the promise, and the caller doesn’t wait for it. Fixed version: async function getUser() { const res = await fetch('/api/user'); if (!res.ok) throw new Error(res.status); return res.json(); } and the caller does const user = await getUser() inside an async function, with try/catch for errors. Note fetch doesn’t reject on 404 or 500, so I check res.ok.”
Traps that make people fail
Not knowing fetch only rejects on network errors, not HTTP errors.
Awaiting one by one is like queuing at three counters one after another. Promise.all sends three people to three counters at the same time.
// slow: one after another (~3s)
const a = await getA(); const b = await getB(); const c = await getC();
// fast: in parallel (~1s)
const [a2, b2, c2] = await Promise.all([getA(), getB(), getC()]);
// keep going even if one fails
const results = await Promise.allSettled([getA(), getB(), getC()]);
Say it like this in the interview
“Promise.all runs them in parallel and rejects as soon as one fails. If partial results are acceptable I use Promise.allSettled. Promise.race and Promise.any are for first-to-finish scenarios like timeouts.”
Inside an async function, code before the first await runs immediately. Everything after await waits for the microtask queue, which runs after the current synchronous code but before timers.
Say it like this in the interview
“1, 2, 4, 3, 5. run starts synchronously and logs 2; await pauses it; 4 logs synchronously; the continuation logs 3 as a microtask; the timeout logs 5 last.”
Start all promises, collect results in the right positions, resolve when all are done, reject as soon as one fails.
function promiseAll(items) {
return new Promise((resolve, reject) => {
const results = [];
let done = 0;
if (items.length === 0) return resolve(results);
items.forEach((item, i) => {
Promise.resolve(item).then((value) => {
results[i] = value;
if (++done === items.length) resolve(results);
}, reject);
});
});
}
Say it like this in the interview
“I return a new Promise, track a counter, store each result at its index so order is preserved, resolve when the counter reaches the length, and reject on the first failure. An empty input resolves immediately.”
JavaScript has one main worker. It runs your code start to finish; slow tasks (timers, network) are handed to the browser or Node. When they’re done, their callbacks wait in queues. When the worker is free, it first empties the promise queue, then takes the next task.
Say it like this in the interview
“The call stack executes synchronous code. Async operations are handled by the environment, which queues callbacks: microtasks (promises, queueMicrotask) and macrotasks (timers, I/O, events). When the stack is empty, all microtasks run, then rendering may happen, then the next macrotask. That’s why long synchronous code freezes the UI.”
“Filter keeps paid orders, map extracts amounts, reduce sums them, starting from 0. None of these mutate the original array. I always pass an initial value to reduce, otherwise an empty array throws.”
Traps that make people fail
Using map when you don’t use its result. That’s what forEach is for.
Spread makes a shallow copy: a new outer box, but nested objects inside are still shared. Changing name only affects the copy; changing address.city changes the shared inner object.
Say it like this in the interview
“Ali Karachi. Spread copies one level deep. For a deep copy I use structuredClone(original).”
Compare values directly if they’re simple; if both are objects, check they have the same keys and compare each value the same way (recursion).
function deepEqual(a, b) {
if (Object.is(a, b)) return true;
if (typeof a !== 'object' || typeof b !== 'object' || !a || !b) return false;
if (Array.isArray(a) !== Array.isArray(b)) return false;
const keysA = Object.keys(a), keysB = Object.keys(b);
if (keysA.length !== keysB.length) return false;
return keysA.every((key) => Object.hasOwn(b, key) && deepEqual(a[key], b[key]));
}
Say it like this in the interview
“Recursive comparison: primitives with Object.is, then type and key count checks, then each key recursively. Production versions handle dates, maps, sets and circular references.”
A Map is a dedicated dictionary: any type of key (even objects), keeps insertion order, has .size, and no accidental clashes with built-in keys like constructor.
Say it like this in the interview
“Map for dynamic key-value collections: any key type, predictable order, fast frequent additions and deletions, built-in size and iteration. Objects for fixed-shape records and JSON. WeakMap when keys are objects whose lifetime I don’t want to extend.”
It loses anything JSON can’t represent: dates become strings, undefined and functions disappear, Maps and Sets become empty objects, and circular references crash.
Say it like this in the interview
“It drops functions and undefined, converts Dates to strings, mangles Map, Set and special numbers, and throws on circular references. structuredClone handles most of these properly, except functions and DOM nodes.”
Decimals in binary aren’t exact (0.1 + 0.2 !== 0.3). Rounding errors on money are unacceptable.
Say it like this in the interview
“Store and calculate in the smallest unit as integers, like cents or paisa, and format only for display with Intl.NumberFormat. For very large values, BigInt or a decimal library. Never compare floats with ===.”
Instead of putting a listener on each of 1,000 list items, put one listener on the parent. Clicks bubble up from the item to the parent, and you check which item was clicked. It also works for items added later.
“Events bubble up the DOM, so one listener on a container can handle events from many children using event.target.closest(). Fewer listeners, less memory, and it works for dynamically added elements.”
When you click a button inside a div, the click first travels down from the page to the button (capturing), then back up through each parent (bubbling). Listeners usually run in the bubbling phase.
Say it like this in the interview
“Events go through capture, target and bubble phases. stopPropagation stops it reaching other elements; preventDefault stops the browser’s default action, like following a link. They’re independent. Bubbling is what makes event delegation work.”
The browser protects users: a page from site-a.com can’t read responses from api-b.com unless api-b.comsays it’s allowed using response headers. The fix is on the server, not in your frontend code.
Say it like this in the interview
“CORS is a browser security policy. The API server must return Access-Control-Allow-Origin for my origin, plus allowed methods and headers for preflight OPTIONS requests, and Allow-Credentials if cookies are involved. Front-end workarounds don’t fix it; in development I can use a dev-server proxy, and in production a same-origin backend route.”
Traps that make people fail
Using mode: 'no-cors'. The response becomes unreadable.
localStorage: stays until cleared, per site, ~5MB, JavaScript only.
sessionStorage: same, but gone when the tab closes.
Cookies: tiny, sent to the server with every request, can expire, can be hidden from JS (HttpOnly).
Say it like this in the interview
“localStorage persists, sessionStorage is per tab, both are synchronous, string-only and readable by any script on the page, so never store tokens there if XSS is possible. Cookies are sent with requests and can be HttpOnly and Secure, which makes them the right place for session identifiers.”
Before certain cross-site requests, the browser first sends an OPTIONS request asking “are you OK with this?”. Only if the server agrees does the real request go.
Say it like this in the interview
“A preflight OPTIONS request happens for non-simple requests: methods like PUT or DELETE, custom headers like Authorization, or Content-Type: application/json. The server must answer with matching Access-Control-Allow-* headers. Access-Control-Max-Age lets the browser cache the result.”
Something keeps collecting things and never lets go: listeners, timers, caches, or references to removed DOM nodes.
Say it like this in the interview
“Classic leaks: event listeners and intervals not removed when components unmount, growing global caches or arrays, closures holding large objects, detached DOM nodes still referenced, and subscriptions like WebSockets never closed. I take heap snapshots in Chrome DevTools before and after repeating an action, compare retained objects, and check the Performance monitor for listener and DOM node counts. Fix with cleanup functions, AbortController, WeakMap, and bounded caches.”
Memoize = remember answers. If the function is called again with the same input, return the saved answer instead of recalculating.
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);
};
}
Say it like this in the interview
“A closure holds a Map from serialised arguments to results. It only works for pure functions, and an unbounded cache can leak memory, so I’d add a size limit in production.”
A Web Worker is a second JavaScript thread in the browser. Heavy calculations there don’t freeze the page.
Say it like this in the interview
“Workers run scripts on a background thread without DOM access, communicating via postMessage. I use them for CPU-heavy tasks: parsing big files, image processing, complex calculations, keeping the main thread responsive. Data is copied or transferred with transferable objects.”
The engine regularly finds objects nothing can reach anymore and frees their memory, so you don’t free memory by hand. But anything still referenced stays.
Say it like this in the interview
“Engines use mark-and-sweep from roots like globals and the stack: unreachable objects are collected, with generational collection for efficiency. Leaks happen when references persist unintentionally: global caches, forgotten listeners or timers, closures and detached DOM nodes.”
Every object has a hidden link to another object (its prototype). If you ask for a property it doesn’t have, JavaScript looks it up the chain. class is nicer syntax for the same system.
Say it like this in the interview
“Objects delegate property lookups to their [[Prototype]], forming a chain ending at Object.prototype. Methods defined in a class live on ClassName.prototype and are shared by all instances. class and extends are syntax over prototypes, with extras like private #fields.”
Prefix the field with #. Code outside the class can’t read or change it at all, not even by accident.
Say it like this in the interview
“#field private class fields and #method() private methods are enforced by the language. The old _underscore convention is only a hint. Closures and WeakMaps were the earlier patterns.”
An iterator is anything that can give you “the next value” on demand. A generator function (function*) is an easy way to make one, pausing at each yield.
Say it like this in the interview
“Objects implementing [Symbol.iterator] work with for...of and spread. Generators create iterators lazily and can model infinite sequences or step-by-step processes. Async generators with for await are useful for paginated APIs.”
Two systems for splitting code into files. CommonJS (require) is Node’s original system, loaded at runtime. ES modules (import) are the official standard, analysed before running, which enables tree-shaking.
Say it like this in the interview
“CommonJS uses require and module.exports, loaded synchronously and dynamically. ESM uses static import/export, supports top-level await and tree-shaking, and is the browser standard. In Node I choose via "type": "module" or .mjs. Dynamic import() loads modules on demand.”
?. means “only continue if the thing before isn’t null or undefined, otherwise give undefined”. ?? means “use this fallback only if the value is null or undefined” (unlike ||, which also replaces 0 and '').
Say it like this in the interview
“Optional chaining short-circuits on null or undefined: user?.address?.city, also fn?.() and arr?.[0]. Nullish coalescing provides a default only for null or undefined, so count ?? 10 keeps 0, whereas count || 10 wouldn’t.”
Email addresses are more varied than most regex patterns expect. Overly strict patterns block real users.
Say it like this in the interview
“Use a simple sanity check like /^[^\s@]+@[^\s@]+\.[^\s@]+$/ or <input type="email">, and confirm by sending a verification email. Perfect email regex is impossible to maintain, and rejecting real customers costs more than a few typos.”
.map only exists on arrays. data is something else: an object (often { results: [...] }), a string, null or a promise.
Say it like this in the interview
“data isn’t an array. I log data and its type: often the API returned an object wrapping the array, an error object, or I forgot to await and have a Promise. I fix the access (data.results.map) and guard with Array.isArray or a default [].”