JavaScript Core
Types and coercion
Section titled “Types and coercion”Q (basic): What are the data types in JavaScript?
Say this (30 sec): There are 8 types. Seven primitives — string, number, bigint, boolean, undefined, null, symbol — and object. Arrays, functions, dates, maps are all objects. Primitives are immutable and compared by value; objects are compared by reference.
Example:
typeof "hi"; // "string"typeof 42; // "number"typeof 10n; // "bigint"typeof undefined; // "undefined"typeof Symbol(); // "symbol"typeof null; // "object" <- historical bugtypeof []; // "object"typeof function(){};// "function" (still an object, typeof just special-cases it)Follow-ups they ask: How do you check for an array? → Array.isArray(x). How do you check for null? → x === null.
Common wrong answer: “null is an object.” No — null is a primitive; typeof null === "object" is a bug kept for backward compatibility.
Q (basic): Difference between null and undefined?
Say this (30 sec): undefined means “not assigned yet” — the engine gives it to uninitialized variables, missing function args, missing properties. null is an intentional “no value” that we assign. null == undefined is true, but null === undefined is false.
Example:
let a; // undefinedconst obj = {};obj.x; // undefinedlet user = null; // explicitly emptyFollow-ups they ask: What does ?? do? → returns the right side only if the left is null or undefined (unlike ||, which also skips 0, "", false).
Q (basic): Difference between == and ===?
Say this (30 sec): === is strict equality — no type conversion, types must match. == is loose equality — it converts types before comparing, which gives surprising results. I always use ===, except x == null which is a short way to check both null and undefined.
Example:
0 == ""; // true0 == "0"; // true"" == "0"; // false (not transitive!)null == undefined; // truenull == 0; // falseNaN == NaN; // false[] == false; // true ([] -> "" -> 0, false -> 0)Follow-ups they ask: How to compare NaN? → Number.isNaN(x) or Object.is(x, NaN). What is Object.is? → like === but Object.is(NaN, NaN) is true and Object.is(0, -0) is false.
Q (basic): What are truthy and falsy values?
Say this (30 sec): Falsy values are exactly: false, 0, -0, 0n, "", null, undefined, NaN. Everything else is truthy — including [], {}, "0", "false".
Example:
if ([]) console.log("runs"); // empty array is truthyconst count = 0;count || 10; // 10 (|| treats 0 as missing)count ?? 10; // 0 (?? only treats null/undefined as missing)Common wrong answer: “An empty array is falsy.” It’s truthy. Check arr.length instead.
Q (mid): How does type coercion work with + and -?
Say this (30 sec): + is overloaded: if either side becomes a string, it concatenates; otherwise it adds numbers. Other math operators (-, *, /) always convert to numbers. Objects are first converted to primitives (via valueOf/toString), which is why [] + {} gives a string.
Example:
"5" + 2; // "52""5" - 2; // 3"5" * "2"; // 10true + 1; // 2[] + []; // ""[] + {}; // "[object Object]"+""; // 0+"abc"; // NaNFollow-ups they ask: Why is 0.1 + 0.2 !== 0.3? → numbers are IEEE-754 doubles; 0.1 can’t be represented exactly. Compare with Math.abs(a - b) < Number.EPSILON or work in integers (paise instead of rupees).
Hoisting, scope and TDZ
Section titled “Hoisting, scope and TDZ”Q (basic): What is hoisting?
Say this (30 sec): Before code runs, the engine sets up all declarations in a scope. var declarations are hoisted and initialized to undefined. Function declarations are hoisted fully — you can call them before they appear. let, const and class are also hoisted but not initialized, so accessing them early throws a ReferenceError — that window is the Temporal Dead Zone.
Example:
console.log(a); // undefinedvar a = 5;
sayHi(); // worksfunction sayHi() { console.log("hi"); }
console.log(b); // ReferenceError: Cannot access 'b' before initializationlet b = 5;
greet(); // TypeError: greet is not a function (greet is undefined)var greet = function () {};Common wrong answer: “let and const are not hoisted.” They are hoisted — that’s why the TDZ error exists instead of falling through to an outer variable.
Q (mid): What is the Temporal Dead Zone?
Say this (30 sec): The TDZ is the time between entering a scope and the line where a let/const/class is declared. During that time the variable exists but can’t be read or written — doing so throws a ReferenceError.
Example:
let x = "outer";{ console.log(x); // ReferenceError, NOT "outer" — inner x is hoisted and in TDZ let x = "inner";}Follow-ups they ask: Does typeof protect you in the TDZ? → No, typeof x also throws in the TDZ (it only returns “undefined” for undeclared variables).
Q (basic): var vs let vs const?
Say this (30 sec): var is function-scoped, can be redeclared, and is hoisted as undefined. let and const are block-scoped and have a TDZ. const can’t be reassigned, but if it holds an object, the object itself can still be mutated. Default to const, use let when you reassign, avoid var.
Example:
const user = { name: "A" };user.name = "B"; // fine — mutationuser = {}; // TypeError — reassignment
for (var i = 0; i < 3; i++) {}console.log(i); // 3 — var leaks out of the blockFollow-ups they ask: How to make an object truly immutable? → Object.freeze(obj) (shallow only).
Q (mid): What is lexical scope and the scope chain?
Say this (30 sec): Lexical scope means a function’s access to variables is decided by where it’s written in the code, not where it’s called. When a variable is used, JS looks in the current scope, then the parent, and so on up to global — that’s the scope chain. If not found, it’s a ReferenceError.
Example:
const x = "global";function outer() { const x = "outer"; function inner() { console.log(x); } return inner;}outer()(); // "outer" — decided by where inner was definedClosures
Section titled “Closures”Q (basic): What is a closure?
Say this (30 sec): A closure is when a function remembers variables from the scope where it was created, even after that outer function has finished running. Every function in JS forms a closure. We use it for data privacy, function factories, memoization, debounce, and React hooks rely on it heavily.
Example:
function createCounter() { let count = 0; // private return { increment: () => ++count, get: () => count, };}const c = createCounter();c.increment(); c.increment();c.get(); // 2 — count is still alive inside the closureFollow-ups they ask: Downside? → closures keep referenced variables in memory, so they can cause leaks if you hold large objects. Where in React? → stale closures: a setInterval inside useEffect with [] deps sees the first render’s state forever.
Q (tricky): Classic loop + setTimeout — what prints and how do you fix it?
Say this (30 sec): With var it prints 3 3 3 because there’s one shared i for the whole function, and by the time the timeouts run the loop has finished. With let, each iteration gets a new binding, so it prints 0 1 2. Pre-ES6 fix was an IIFE to capture the value.
Example:
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i), 0); // 3 3 3for (let i = 0; i < 3; i++) setTimeout(() => console.log(i), 0); // 0 1 2
// old fixfor (var i = 0; i < 3; i++) { ((j) => setTimeout(() => console.log(j), 0))(i); // 0 1 2}Q (mid): What is a stale closure in React?
Say this (30 sec): Each render creates new functions that close over that render’s state. If a callback created in an old render keeps running — like a setInterval set up in an effect with empty deps — it keeps reading the old value. Fix: use the functional updater setCount(c => c + 1), add the value to deps, or read from a ref.
Example:
useEffect(() => { const id = setInterval(() => setCount(count + 1), 1000); // stuck at 1 return () => clearInterval(id);}, []);
// fixuseEffect(() => { const id = setInterval(() => setCount(c => c + 1), 1000); return () => clearInterval(id);}, []);this, call, apply, bind
Section titled “this, call, apply, bind”Q (mid): How is "this" determined?
Say this (30 sec): this depends on how the function is called, in priority order: (1) new — this is the new object; (2) call/apply/bind — this is what you pass; (3) method call obj.fn() — this is obj; (4) plain call fn() — undefined in strict mode, globalThis in sloppy mode. Arrow functions ignore all of this and use this from the surrounding scope.
Example:
const user = { name: "Riya", regular() { return this.name; }, arrow: () => this?.name,};user.regular(); // "Riya"user.arrow(); // undefined — arrow takes this from module/global scopeconst fn = user.regular;fn(); // undefined / TypeError in strict mode — lost the objectFollow-ups they ask: Why does this get lost in callbacks like setTimeout(obj.method)? → you’re passing the function alone; it’s called plainly. Fix with obj.method.bind(obj) or an arrow wrapper.
Common wrong answer: “this refers to the function itself” or “where the function is defined.” It’s about the call site (except arrows).
Q (basic): Difference between call, apply and bind?
Say this (30 sec): All three set this. call invokes immediately with arguments listed one by one. apply invokes immediately with arguments as an array. bind doesn’t invoke — it returns a new function with this (and optionally some args) permanently fixed.
Example:
function greet(greeting, punct) { return `${greeting}, ${this.name}${punct}`; }const p = { name: "Aman" };greet.call(p, "Hi", "!"); // "Hi, Aman!"greet.apply(p, ["Hi", "!"]); // "Hi, Aman!"const bound = greet.bind(p, "Hey");bound("?"); // "Hey, Aman?"Follow-ups they ask: Can you rebind a bound function? → No, bind on a bound function doesn’t change this. Does bind work on arrow functions? → It can pre-fill args, but can’t change this.
Q (mid): Arrow functions vs regular functions?
Say this (30 sec): Arrows have no own this, arguments, super, or prototype, so they can’t be used as constructors with new. They take this lexically, which makes them great for callbacks. Don’t use them as object methods if you need this to be the object.
Example:
class Timer { seconds = 0; start() { setInterval(() => this.seconds++, 1000); // arrow keeps class instance as this }}const Arrow = () => {};new Arrow(); // TypeError: Arrow is not a constructorPrototypes and classes
Section titled “Prototypes and classes”Q (mid): What is prototypal inheritance?
Say this (30 sec): Every object has a hidden link, [[Prototype]], to another object. When you read a property that isn’t on the object, JS walks up this prototype chain until it finds it or hits null. Functions have a .prototype property, and objects created with new Fn() get Fn.prototype as their prototype. Classes are built on this same mechanism.
Example:
const animal = { eats: true };const dog = Object.create(animal);dog.barks = true;dog.eats; // true — found on prototypeObject.getPrototypeOf(dog) === animal; // true
[].__proto__ === Array.prototype; // trueArray.prototype.__proto__ === Object.prototype; // trueObject.prototype.__proto__; // null — end of chainFollow-ups they ask: __proto__ vs prototype? → __proto__ (better: Object.getPrototypeOf) is an object’s link to its prototype. .prototype is a property on constructor functions that becomes the __proto__ of instances.
Q (mid): Are JS classes just syntactic sugar?
Say this (30 sec): Mostly — they use prototypes underneath. But there are real differences: class code always runs in strict mode, classes must be called with new, they’re in the TDZ until declared (not usable before the line), methods are non-enumerable, and they support private #fields and static blocks which have no clean prototype equivalent.
Example:
class Account { #balance = 0; // truly private static count = 0; deposit(amt) { this.#balance += amt; return this; } get balance() { return this.#balance; }}class Savings extends Account { constructor() { super(); } // must call super() before using this}Follow-ups they ask: What does new do? → creates an empty object, sets its prototype to Fn.prototype, runs the function with this = that object, returns the object (unless the function returns another object).
Event loop
Section titled “Event loop”Q (basic): Explain the event loop.
Say this (30 sec): JS runs on a single thread with one call stack. Async work like timers, network and DOM events is handled by the browser (or Node), and when it finishes, its callback is queued. The event loop waits until the call stack is empty, then drains the entire microtask queue (promise callbacks, await continuations, queueMicrotask, MutationObserver), then takes one macrotask (setTimeout, setInterval, I/O, UI events), and repeats. The browser can render between macrotasks.
Example:
console.log("1");setTimeout(() => console.log("2"), 0);Promise.resolve().then(() => console.log("3"));console.log("4");// 1 4 3 2Follow-ups they ask: Does setTimeout(fn, 0) run immediately? → No, it runs after current sync code and all microtasks; browsers also clamp nested timers to ~4ms. Can microtasks block rendering? → Yes, a microtask that keeps queuing microtasks starves the page.
Common wrong answer: “Promises run in parallel / on another thread.” Promise callbacks run on the main thread; only the underlying I/O happens elsewhere.
Q (tricky): Predict the output — async/await ordering.
Say this (30 sec): Code before the first await runs synchronously. Everything after an await is scheduled as a microtask.
Example:
async function a() { console.log("a1"); await b(); console.log("a2");}async function b() { console.log("b"); }
console.log("start");a();console.log("end");// start, a1, b, end, a2Q (tricky): Predict the output — mixed timers and promises.
Say this (30 sec): Sync first, then all microtasks (including ones queued by microtasks), then each timer one at a time, draining microtasks after each.
Example:
console.log("A");setTimeout(() => { console.log("B"); Promise.resolve().then(() => console.log("C"));}, 0);setTimeout(() => console.log("D"), 0);Promise.resolve() .then(() => console.log("E")) .then(() => console.log("F"));queueMicrotask(() => console.log("G"));console.log("H");// A H E G F B C DWhy: sync → A, H. Microtasks queued: E, G. E runs and queues F, so order is E, G, F. Then timer 1: B, and its microtask C runs before timer 2. Then D.
Q (tricky): Predict the output — Promise constructor.
Say this (30 sec): The executor function passed to new Promise runs synchronously. Only .then callbacks are async.
Example:
console.log(1);new Promise((resolve) => { console.log(2); resolve(); console.log(3); // still runs — resolve doesn't stop execution}).then(() => console.log(4));console.log(5);// 1 2 3 5 4Promises and async/await
Section titled “Promises and async/await”Q (basic): What is a Promise and its states?
Say this (30 sec): A Promise is an object representing a future value. It’s in one of three states: pending, fulfilled, or rejected. Once settled it can’t change. You consume it with .then, .catch, .finally, or await. It solves callback hell and gives proper error propagation through the chain.
Example:
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));wait(500) .then(() => fetch("/api/user")) .then((res) => res.json()) .catch((err) => console.error(err)) .finally(() => setLoading(false));Follow-ups they ask: What does .then return? → Always a new promise, which is why chaining works. Returning a value resolves it; throwing rejects it.
Q (mid): Promise.all vs allSettled vs race vs any?
Say this (30 sec):
all— waits for all to fulfill; rejects immediately on the first rejection. Use when you need every result.allSettled— waits for all to finish, never rejects; gives{status, value | reason}for each. Use for “show what succeeded”.race— settles with the first to settle, success or failure. Use for timeouts.any— fulfills with the first success; rejects withAggregateErroronly if all fail.
Example:
const timeout = (ms) => new Promise((_, rej) => setTimeout(() => rej(new Error("timeout")), ms));const data = await Promise.race([fetch("/api"), timeout(5000)]);
const results = await Promise.allSettled([fetchA(), fetchB()]);results.filter(r => r.status === "fulfilled").map(r => r.value);Common wrong answer: “Promise.all cancels the other promises when one fails.” It doesn’t — the others keep running; their results are just ignored.
Q (mid): How does async/await relate to promises?
Say this (30 sec): async/await is syntax over promises. An async function always returns a promise. await pauses that function (not the thread) until the promise settles, then resumes it as a microtask. Errors become exceptions you catch with try/catch.
Example:
async function loadUser(id) { try { const res = await fetch(`/api/users/${id}`); if (!res.ok) throw new Error(`HTTP ${res.status}`); // fetch doesn't reject on 404/500! return await res.json(); } catch (err) { console.error(err); throw err; }}Follow-ups they ask: Does fetch reject on 404? → No, only on network failure/abort. You must check res.ok.
Q (mid): Sequential vs parallel await — what's the difference?
Say this (30 sec): Awaiting one after another runs them sequentially, so total time is the sum. If they’re independent, start them together and await Promise.all, so total time is the slowest one.
Example:
// slow: ~2sconst user = await getUser();const posts = await getPosts();
// fast: ~1sconst [user2, posts2] = await Promise.all([getUser(), getPosts()]);Follow-ups they ask: Does await work in forEach? → No, forEach ignores returned promises. Use for...of for sequential or Promise.all(arr.map(...)) for parallel.
Q (mid): How do you handle errors in async code?
Say this (30 sec): With async/await use try/catch/finally. With chains use .catch. A try/catch around a setTimeout won’t catch errors thrown inside its callback because it runs later on a different stack. Unhandled rejections trigger unhandledrejection in the browser and can crash a Node process. In React, use error boundaries for render errors — they don’t catch async or event handler errors.
Example:
try { setTimeout(() => { throw new Error("boom"); }, 0);} catch (e) { // never runs}
window.addEventListener("unhandledrejection", (e) => log(e.reason));Functional patterns and copying
Section titled “Functional patterns and copying”Q (basic): map vs filter vs reduce vs forEach?
Say this (30 sec): map returns a new array of the same length with transformed items. filter returns a new array with items that pass the test. reduce boils the array down to a single value — sum, object, grouped map. forEach just iterates and returns undefined; you can’t break out of it. None of them mutate the original array (unless your callback does).
Example:
const cart = [{ name: "pen", price: 10, qty: 2 }, { name: "book", price: 200, qty: 1 }];const names = cart.map(i => i.name); // ["pen", "book"]const pricey = cart.filter(i => i.price > 50); // [{book}]const total = cart.reduce((sum, i) => sum + i.price * i.qty, 0); // 220Follow-ups they ask: Why pass an initial value to reduce? → Without it, an empty array throws a TypeError, and the first element is used as the accumulator, which breaks when you’re building an object. Which array methods mutate? → push, pop, shift, unshift, splice, sort, reverse, fill. ES2023 added non-mutating toSorted, toReversed, toSpliced, with.
Q (mid): Shallow copy vs deep copy?
Say this (30 sec): A shallow copy copies the top level only; nested objects are still shared references. Spread and Object.assign are shallow. For deep copy, use structuredClone — it handles nested objects, Dates, Maps, Sets and circular references. JSON.parse(JSON.stringify()) is a hack: it drops undefined and functions, turns Dates into strings, and throws on circular refs.
Example:
const a = { user: { name: "A" } };const shallow = { ...a };shallow.user.name = "B";a.user.name; // "B" — shared!
const deep = structuredClone(a);deep.user.name = "C";a.user.name; // still "B"Follow-ups they ask: What can’t structuredClone copy? → functions and DOM nodes (throws DataCloneError), and class instances lose their prototype (become plain objects).
Q (basic): What are debounce and throttle?
Say this (30 sec): Both limit how often a function runs. Debounce waits until calls stop for X ms, then runs once — good for search-as-you-type and resize-end. Throttle runs at most once every X ms during continuous calls — good for scroll and mousemove handlers. (Implementations are on the Machine Coding page.)
Example:
input.addEventListener("input", debounce(search, 300)); // fires 300ms after user stops typingwindow.addEventListener("scroll", throttle(onScroll, 100)); // fires at most every 100msQ (mid): Map vs Object, Set vs Array, WeakMap?
Say this (30 sec): Map allows any key type (objects too), keeps insertion order, has .size, and is faster for frequent add/remove. Objects only have string/symbol keys. Set stores unique values — easy dedupe with [...new Set(arr)]. WeakMap keys must be objects and are held weakly, so they don’t prevent garbage collection — useful for caching data about DOM nodes or objects without leaking memory.
Example:
const unique = [...new Set([1, 2, 2, 3])]; // [1, 2, 3]const cache = new WeakMap();cache.set(domNode, { clicks: 0 }); // auto-cleaned when domNode is goneModules and memory
Section titled “Modules and memory”Q (mid): ES Modules vs CommonJS?
Say this (30 sec): CommonJS (require/module.exports) is Node’s original system: synchronous, dynamic (you can require inside an if), and exports are a copied value. ES Modules (import/export) are the standard: imports are static and hoisted, which enables tree-shaking; they’re loaded asynchronously; exports are live bindings; they’re strict mode by default; and they support top-level await. In Node you opt in with "type": "module" or .mjs.
Example:
// CommonJSconst fs = require("fs");module.exports = { read };
// ESMimport fs from "node:fs";export function read() {}const { heavy } = await import("./heavy.js"); // dynamic import for code splittingFollow-ups they ask: Why does tree-shaking need ESM? → bundlers can only remove unused exports when imports are statically analyzable. Can ESM use __dirname? → No; use import.meta.dirname (newer Node) or import.meta.url.
Q (mid): How does garbage collection work? What causes memory leaks?
Say this (30 sec): JS uses automatic GC based on reachability — the mark-and-sweep algorithm marks everything reachable from roots (globals, the current call stack) and frees the rest. Modern engines like V8 also use generational collection: young objects are collected often, long-lived ones less often. Leaks happen when something unintentionally stays reachable.
Common leaks:
- Timers / intervals never cleared
- Event listeners not removed (classic in React effects without cleanup)
- Detached DOM nodes still referenced in JS
- Closures or global caches holding large objects
- Growing arrays/maps used as caches without limits
Follow-ups they ask: How do you find a leak? → Chrome DevTools Memory tab: take heap snapshots before and after an action and compare, look for detached nodes.
Q (mid): What's new in modern JavaScript (ES2023-ES2025) that you've used?
Say this (30 sec): Pick 2-3 you actually know:
- ES2023:
toSorted,toReversed,with(immutable array updates — great for React state),findLast. - ES2024:
Object.groupBy,Promise.withResolvers. - ES2025: Set methods like
union/intersection, iterator helpers. - Earlier but common: optional chaining
?., nullish??,structuredClone,Array.prototype.at(-1).
Example:
const sorted = items.toSorted((a, b) => a.price - b.price); // original untouchedconst byType = Object.groupBy(items, (i) => i.type);const last = items.at(-1);Output-guessing round
Section titled “Output-guessing round”Q (tricky): typeof checks
console.log(typeof null, typeof NaN, typeof [], typeof undefined, typeof typeof 1);Answer: object number object undefined string — typeof 1 is "number", and typeof "number" is "string".
Q (tricky): [1, 2, 3].map(parseInt)
console.log(["1", "2", "3"].map(parseInt));Answer: [1, NaN, NaN]. map passes (value, index), so calls are parseInt("1", 0) → 1 (radix 0 means default 10), parseInt("2", 1) → NaN (invalid radix), parseInt("3", 2) → NaN (3 isn’t a binary digit). Fix: .map(Number).
Q (tricky): Default sort
console.log([10, 1, 5, 100].sort());Answer: [1, 10, 100, 5]. Default sort converts to strings and compares lexicographically. Fix: .sort((a, b) => a - b).
Q (tricky): Hoisting with same name
var x = 1;function test() { console.log(x); var x = 2;}test();Answer: undefined. The inner var x is hoisted to the top of test, shadowing the outer x.
Q (tricky): this inside a nested function
const obj = { name: "obj", outer() { function inner() { return this?.name; } const arrow = () => this.name; return [inner(), arrow()]; },};console.log(obj.outer());Answer: [undefined, "obj"]. inner() is a plain call, so this is undefined (module/strict) or the global object. The arrow takes this from outer, which is obj.
Q (tricky): Object keys coercion
const a = {};const b = { key: "b" };const c = { key: "c" };a[b] = 123;a[c] = 456;console.log(a[b]);Answer: 456. Object keys are strings, so both b and c become "[object Object]" — the same key. Use a Map for object keys.
Q (tricky): Comparisons with null
console.log(null == 0, null > 0, null >= 0);Answer: false false true. == has a special rule: null only equals undefined. But > and >= convert null to 0, so 0 >= 0 is true.
Q (tricky): Closure counter
function make() { let n = 0; return () => ++n;}const f = make();const g = make();console.log(f(), f(), g());Answer: 1 2 1. Each call to make creates a separate closure with its own n.
Q (tricky): Reference vs value
let a = { n: 1 };let b = a;b.n = 2;b = { n: 3 };console.log(a.n);Answer: 2. b.n = 2 mutates the shared object. b = {...} only rebinds b; a still points to the original.
Q (tricky): Promise chain with throw
Promise.resolve(1) .then((x) => { throw new Error("fail"); }) .then(() => console.log("A")) .catch(() => console.log("B")) .then(() => console.log("C"));Answer: B C. The throw skips A, .catch handles it, and since .catch returns a fulfilled promise, C still runs.
Q (tricky): async function return value
async function f() { return 1; }console.log(f());f().then(console.log);Answer: First log prints Promise {<fulfilled>: 1} (a promise, not 1). Then 1 logs asynchronously.
Q (tricky): Floating point and NaN
console.log(0.1 + 0.2 === 0.3, NaN === NaN, [NaN].includes(NaN), [NaN].indexOf(NaN));Answer: false false true -1. includes uses SameValueZero (finds NaN); indexOf uses === (doesn’t).
Q (tricky): Spread is shallow
const orig = { a: 1, nested: { b: 2 } };const copy = { ...orig };copy.a = 10;copy.nested.b = 20;console.log(orig.a, orig.nested.b);Answer: 1 20. Top-level a was copied; nested is the same object in both.