It is 11 at night in Visakhapatnam, and Karan has a frontend interview at ten the next morning. He has read about scope, closures and promises many times, so he opens a list of practice questions to warm up. The first one shows six lines with a setTimeout, a Promise.resolve().then() and an async function, and asks for the order of the output. Karan writes 1 4 6 2 3 5 with confidence, because the timer was written first and has a delay of zero. He runs it in Node.js and gets 1 4 6 3 5 2. He knows every topic by name, yet he still got the answer wrong. How do you revise so that you can actually predict what code does, the way interviewers expect?
This post, Part 2 after JavaScript Part 1, is built for that night-before revision. Each topic gets a short recap, one strong example and a link to the full chapter. Most of the space goes to what the chapters don't give you: output puzzles, interview questions with model answers, "spot the bug" exercises and a one-page cheat sheet. Every snippet was run on Node.js v24, and the outputs shown are real.
How to Use This Revision Guide
Try each puzzle on paper before you open the answer, and say the reason out loud, because interviewers always ask "why?". If a recap feels new rather than rusty, read the full chapter first.
| Topic | Full chapter for depth |
|---|---|
| Scope, scope chain, block scope | Chapter 11: Scope and the Scope Chain |
| Hoisting and the Temporal Dead Zone | Chapter 10: Hoisting |
| Functions, arrow functions, IIFE | Chapter 6: Functions |
this, call, apply, bind, classes | JavaScript Advanced Concepts |
| Closures and the event loop | Chapter 12: Closures & Event Loop |
| Promises and async/await | Chapter 13: Promises & Async Await |
Type conversion, == vs ===, NaN | Chapter 4: Operators and Type Conversion |
| String and array methods | Chapter 7: Objects and Arrays |
1. Scope, var/let/const and Hoisting
Scope is the area of code where a variable is visible. Global scope is visible everywhere; a var inside a function has function scope; let and const have block scope, living only inside the nearest curly braces. To find a name, JavaScript searches the current scope, then each enclosing one up to global. That path is the scope chain, and it is fixed by where code is written, not where it is called.
var company = "WhosGeek"; // global scope
function outer() {
let department = "Engineering"; // function scope of outer
if (true) {
var leaked = "var ignores blocks";
let team = "Frontend"; // block scope
}
function inner() {
console.log(company, department); // found by walking up the scope chain
}
inner(); // WhosGeek Engineering
console.log(leaked); // var ignores blocks
console.log(typeof team); // undefined (team does not exist here)
}
outer();
Hoisting means JavaScript registers every declaration in a scope before any line runs. A var starts as undefined. A let or const stays uninitialised, and reading it before its line throws a ReferenceError; that window is the Temporal Dead Zone (TDZ). Function declarations are hoisted with their body, so you can call them above their line. The full scope story is in Chapter 11: Scope and the Scope Chain, and hoisting has its own Chapter 10.
var | let | const | |
|---|---|---|---|
| Scope | Function | Block | Block |
| Reassign | Yes | Yes | No (TypeError) |
| Redeclare in same scope | Yes, silently | No (SyntaxError) | No (SyntaxError) |
| Read before declaration | undefined | ReferenceError (TDZ) | ReferenceError (TDZ) |
| New copy per loop round | No, one shared variable | Yes | Yes (in for...of) |
Also remember: const PI = 3.14; PI = 5; throws TypeError: Assignment to constant variable., but const cart = {}; cart.items = 2; works, because const blocks reassignment, not changes inside an object.
Output Puzzles: Scope and Hoisting
// Puzzle 1
var a = 1;
function f() {
console.log(a);
var a = 2;
}
f();
Show answer
Output: undefined. Many people expect 1 from the global a. But the var a inside f is hoisted to the top of f and set to undefined, so the local a shadows (hides) the global one before the console.log line runs. The assignment a = 2 has not happened yet.
// Puzzle 2
for (var i = 0; i < 3; i++) setTimeout(() => console.log("var", i), 0);
for (let j = 0; j < 3; j++) setTimeout(() => console.log("let", j), 0);
Show answer
Output: var 3 three times, then let 0, let 1, let 2. The timers run only after both loops finish. With var there is one shared i, and by then it is 3. With let, each loop round gets a fresh j, so each arrow function closes over its own copy.
// Puzzle 3
let x = 1;
{
console.log(x);
let x = 2;
}
Show answer
Output: ReferenceError: Cannot access 'x' before initialization. The inner block has its own x, which is hoisted to the top of the block and sits in the TDZ. JavaScript does not fall back to the outer x, because the name already exists in the nearer scope. This proves that let is hoisted; it is just not initialised.
// Puzzle 4
hello();
const hello = function () { console.log("Hi"); };
// and separately:
hi();
var hi = function () { console.log("Hi"); };
Show answer
Output: the first throws ReferenceError: Cannot access 'hello' before initialization, and the second throws TypeError: hi is not a function. In both cases only the variable is hoisted, not the function stored in it. With const the variable is in the TDZ; with var it is undefined, and calling undefined() is a type error. A function declaration (function hey() {}) would have worked in either position.
Interview Questions with Model Answers
Q: Why were let and const added if var already worked? Model answer: "var ignores blocks, so a variable declared inside an if or a loop leaks into the whole function, and it can be redeclared by mistake without any error. Reading it early gives undefined instead of an error, which hides bugs. let and const are block scoped, cannot be redeclared, and throw in the TDZ, so mistakes show up immediately."
Q: Is let hoisted? Model answer: "Yes, but it is not initialised until its line runs, so access before that throws. That window is the Temporal Dead Zone." Puzzle 3 is the proof.
2. Types and Equality Traps: undefined, null, NaN, Coercion and Strict Mode
Three "empty" situations get mixed up. undefined means declared but never given a value; null means a developer set it to "nothing" on purpose; undeclared means it was never declared, and reading it throws a ReferenceError. Picture parking: undefined is a slot with no car assigned yet, null is a slot marked "kept empty", and undeclared is a slot never painted on the ground.
let username;
console.log(username); // undefined
let user = null;
console.log(user); // null
console.log(typeof username, typeof null); // undefined object
console.log(undefined == null, undefined === null); // true false
console.log(typeof notDeclared); // undefined (typeof does not throw)
console.log(notDeclared); // ReferenceError: notDeclared is not defined
console.log(typeof NaN, Number("hello")); // number NaN
console.log(NaN === NaN, Number.isNaN(NaN)); // false true
console.log(isNaN("hello"), Number.isNaN("hello")); // true false
console.log([NaN].includes(NaN), [NaN].indexOf(NaN)); // true -1
NaN ("Not a Number") is a number-type value that marks a failed calculation, so typeof NaN is "number". It is not equal even to itself, so check with Number.isNaN(value). The older global isNaN() converts first, which is why it calls "hello" NaN.
Type coercion is JavaScript converting types on its own. + joins strings if either side is a string; other arithmetic operators convert to numbers. == converts before comparing; === does not. Chapter 4 lists all the rules.
console.log("5" + 2, "5" - 2); // 52 3
console.log(true + 1, false + 5); // 2 5
console.log("" + 5, typeof ("" + 5)); // 5 string
console.log(5 == "5", 5 === "5"); // true false
console.log(0 == "", 0 == "0", "" == "0"); // true true false
console.log(null == 0, null >= 0); // false true
The last two lines are favourite trick questions. 0 equals both "" and "0", yet those two strings are not equal to each other. And null >= 0 is true while null == 0 is false, because >= converts null to 0 but == has a special rule: null equals only undefined. That inconsistency is your model answer to "why use ===?".
Strict Mode
Strict mode (ES5, switched on with "use strict";) turns silent mistakes into errors. Assigning to an undeclared variable creates an accidental global in normal mode but throws in strict mode, and duplicate parameter names are rejected. Classes and ES modules are always strict.
function sloppy() { totalAmount = 500; } // no let/const/var
sloppy();
console.log(globalThis.totalAmount); // 500 (an accidental global)
"use strict"; // at the top of another file
totalAmount = 500; // ReferenceError: totalAmount is not defined
function sum(a, a) {} // SyntaxError: Duplicate parameter name not allowed in this context
name = "Alex" to show strict mode throwing. In a browser that does not throw, even in strict mode, because name already exists as window.name. Use a name that is not a built-in global, like totalAmount, when you demonstrate this.3. Functions and this
A function is a reusable block of code: define a task once, call it whenever you need it. Interviewers like to ask how the different forms differ; Chapter 6 explains each one at length.
| Form | Example | Hoisted? | Own this? |
|---|---|---|---|
| Declaration | function add(a, b) { return a + b; } | Fully (callable before its line) | Yes |
| Expression | const multiply = function (a, b) { return a * b; }; | Only the variable | Yes |
| Anonymous (as a callback) | button.addEventListener("click", function () { ... }) | Not applicable | Yes |
| Arrow | const add = (a, b) => a + b; | Only the variable | No, uses the surrounding this |
| IIFE | (function () { var secret = "hidden"; })(); | Runs at once | Yes |
| Generator | function* ids() { yield 1; } | Fully | Yes |
An anonymous function has no name and must be used as a value, typically a callback; function () {} alone on a line is a syntax error. An IIFE ("iffy") runs the moment it is created, and before let it was the standard way to make private variables. A generator (function*) pauses at each yield:
(function () {
var secret = "hidden";
console.log(secret); // hidden
})();
console.log(typeof secret); // undefined (not visible outside)
function* orderIds() {
let n = 1;
while (true) yield n++;
}
const gen = orderIds();
console.log(gen.next().value, gen.next().value, gen.next().value); // 1 2 3
Output Puzzles: this
// Puzzle 5
const person = {
name: "Alex",
regular: function () { console.log(this.name); },
arrow: () => { console.log(this.name); },
};
person.regular();
person.arrow();
Show answer
Output in Node.js: Alex, then undefined. A regular function gets this from the call, so person.regular() sets it to person. An arrow function has no this of its own and uses the surrounding one, the module scope. In a browser script it prints an empty line, because this is window and window.name is "". Either way, not "Alex".
// Puzzle 6
class Student {
constructor(name) { this.name = name; }
greet() { return `Hi ${this.name}`; }
}
const s = new Student("Karan");
const greet = s.greet;
console.log(greet());
Show answer
Output: TypeError: Cannot read properties of undefined (reading 'name'). Copying the method into a variable loses its object, and since class bodies are strict, a plain call gives this === undefined. Passing s.greet as a callback does the same. Fix it with s.greet.bind(s) or an arrow wrapper () => s.greet(). The advanced concepts post covers call, apply and bind in full.
4. Closures and the Scope Chain
A closure is a function together with the variables it could see where it was created. An inner function that is returned or passed elsewhere keeps access to those outer variables after the outer function has finished. The usual picture is notes you carry home from a closed office, with one correction that matters in interviews: a closure keeps a live link to the variable, not a frozen copy of its value.
function createCounter() {
let count = 0; // private: nothing outside can touch it
return () => ++count;
}
const c1 = createCounter();
const c2 = createCounter();
c1(); c1();
console.log(c1(), c2()); // 3 1 (each call to createCounter makes a new count)
Closures power data privacy, counters, caching, event handlers and React hooks. Chapter 12 explains them step by step with a bank and ATM analogy.
Output Puzzles: Closures
// Puzzle 7
let price = 100;
const show = () => console.log(price);
price = 200;
show();
Show answer
Output: 200. The arrow function reads price when it runs, through the scope chain, not when it was created. A closure holds a reference to the variable, so later changes are visible. This is the same reason Puzzle 2 printed 3 three times with var.
// Puzzle 8
function createCounter() {
let count = 0;
return function () { return count++; };
}
const counter = createCounter();
console.log(counter(), counter(), counter());
Show answer
Output: 0 1 2. count++ is the postfix form: it returns the old value, then adds one. The earlier counter example used ++count (prefix), which adds first and returns the new value, so it started at 1. Interviewers sometimes change only this one character to see if you notice.
Interview Question: "Write a function that runs only once"
A common follow-up to "what is a closure?". Think of a "Pay ₹499" button that must not charge twice on a double-tap.
function once(fn) {
let done = false, result;
return (...args) => {
if (!done) {
done = true;
result = fn(...args);
}
return result;
};
}
const pay = once((amount) => {
console.log(`Charged ₹${amount}`);
return "txn-1";
});
console.log(pay(499), pay(499));
// Charged ₹499
// txn-1 txn-1
Model answer: "done and result live in once's scope. The returned function closes over them, so every call sees the same two variables and nothing outside can reset them." A real payment must also be protected on the server.
5. String and Array Methods: Quick Revision
String methods never change the original, because strings are immutable; they return a new string. Array methods are split: some return a new array, others change (mutate) it in place, and knowing which is which is the most tested fact here. Chapter 7 has the full list.
| Method | Returns | Changes original? | Example result |
|---|---|---|---|
str.trim() | New string without leading/trailing spaces | No | " hello world " length 17 → 11 |
str.slice(0, 4) / slice(-6) | Part of string; negatives count from the end | No | "Java" / "Script" |
str.substring(3, 1) | Part of string; swaps reversed arguments, treats negatives as 0 | No | "Hello" → "el" |
str.charAt(4) / str.indexOf("W") | One character / first position or -1 | No | "S" / 6 in "Hello World" |
push / unshift | New length | Yes (add at end / start) | [1,2,3].push(4) → 4 |
pop / shift | Removed element | Yes (remove last / first) | [1,2,3,4].pop() → 4 |
splice(1, 2, "new") | Array of removed items | Yes | [1,2,3,4] becomes [1,"new",4], returns [2,3] |
slice(1, 3) | New array copy of a part | No | [2,3], original unchanged |
map / filter | New array (same length / matching items) | No | [2,4,6] |
find / findIndex | First match or undefined / its index or -1 | No | [5,12,8,130].find(n => n > 10) → 12 |
forEach | Always undefined | No (unless your callback mutates) | Use it only for side effects like logging |
reduce | One value built with an accumulator | No | [3,4,5,6] → 18 |
map, filter, find, forEach and reduce are higher-order functions because they take a function as an argument. In reduce, the accumulator carries the running result: cart.reduce((total, item) => total + item.price, 0) gives 548 for items at ₹199 and ₹349.
Output Puzzles: Strings and Arrays
// Puzzle 9
console.log("Hello".substring(3, 1), "Hello".slice(3, 1), "Hello".substring(-2, 3));
console.log([1, 2, 3].map(parseInt));
console.log([10, 1, 5, 100].sort());
console.log([].reduce((a, b) => a + b));
Show answer
Output: el Hel (the middle value is an empty string), then [ 1, NaN, NaN ], then [ 1, 10, 100, 5 ], then TypeError: Reduce of empty array with no initial value. substring swaps reversed arguments but slice does not, so slice(3, 1) is empty. map passes three arguments (value, index, array), and parseInt reads the index as a radix: parseInt("2", 1) and parseInt("3", 2) are both NaN. sort() without a compare function sorts as strings, so use sort((a, b) => a - b) for numbers. And always give reduce a starting value.
price * 1.18. Try it with ₹499: 499 * 1.18 gives 588.8199999999999, because decimals like 1.18 cannot be stored exactly in binary. For money, work in whole paise or round once at the end, for example Math.round(amount * 118) / 100, which gives 588.82.6. Map, Set, WeakMap and WeakSet
A Map stores key–value pairs where the key can be any type, even an object, and keeps insertion order. A Set stores unique values. A WeakMap takes only object keys and a WeakSet holds only objects. "Weak" means they don't keep objects alive: once nothing else references an object, the garbage collector may remove it and its entry. That is why weak collections have no size and cannot be looped over, and why they suit data attached to objects, like a per-element cache, without memory leaks.
const map = new Map();
const key = {};
map.set(1, "One").set("1", "String one").set(key, "Object");
console.log(map.get(1), map.get("1"), map.get(key), map.get({})); // One String one Object undefined
const emails = ["alex@gmail.com", "alex@gmail.com", "john@gmail.com", "Alex@Gmail.com "];
console.log([...new Set(emails)]);
// [ 'alex@gmail.com', 'john@gmail.com', 'Alex@Gmail.com ' ]
console.log([...new Set(emails.map((e) => e.trim().toLowerCase()))]);
// [ 'alex@gmail.com', 'john@gmail.com' ]
const ws = new WeakSet();
ws.add({ name: "Alex" }); // fine
ws.add(10); // TypeError: Invalid value used in weak set
map.get({}) is undefined because Map compares object keys by reference, and a Set removes only exact duplicates, so clean the data first.
// Puzzle 10
const obj = {};
const a = { id: 1 }, b = { id: 2 };
obj[a] = "first";
obj[b] = "second";
console.log(Object.keys(obj), obj[a]);
Show answer
Output: [ '[object Object]' ] second. Plain object keys are always strings (or symbols), so both objects turn into the same key "[object Object]" and the second write overwrites the first. This is exactly the problem Map solves. It is a strong answer to "when would you use a Map instead of an object?"
Two corrections to the earlier comparison. First, Map keys are unique, but Map values can repeat: new Map([["a", 1], ["b", 1]]) is valid. Second, "Map is faster than an object" is not a general rule. MDN describes Map as performing better in scenarios with frequent additions and removals of keys; for a fixed record like { name, age }, a plain object is the normal choice.
7. Functional Programming, Prototypes, Classes and OOP
Functional Programming in Brief
Functional programming builds programs from small functions that avoid changing outside data, like a factory with separate machines for cutting, painting and packing. A pure function returns the same output for the same input and changes nothing outside. Functions are first-class: they can be stored, passed and returned. A higher-order function takes or returns a function. Currying turns a multi-argument function into a chain of one-argument functions, so you can pre-fill some arguments.
let total = 0;
function addImpure(value) { total += value; return total; } // depends on outside data
console.log(addImpure(5), addImpure(5)); // 5 10 (same input, different output)
function processUser(name, callback) { return callback(name); }
console.log(processUser("Alex", (n) => `Hello ${n}`)); // Hello Alex
function curryAdd(a) {
return function (b) {
return function (c) { return a + b + c; };
};
}
console.log(curryAdd(1)(2)(3)); // 6
const add10 = curryAdd(10);
console.log(add10(5)(2)); // 17
const withTax = (ratePercent) => (amount) => Math.round(amount * (100 + ratePercent)) / 100;
const gst18 = withTax(18);
console.log(gst18(1000), gst18(499)); // 1180 588.82
The last example is currying with a practical use: configure the rate once, reuse gst18 everywhere. Each curried layer is also a closure, which is why interviewers often ask closures and currying together.
Constructor Functions, Prototypes and Classes
Before ES2015, similar objects came from a constructor function called with new, with methods on its shared prototype, so a thousand users share one copy of each method. class is cleaner syntax ("syntactic sugar") over the same prototypes, with differences: classes are strict, need new, and sit in the TDZ before their line.
function Person(name, age) { this.name = name; this.age = age; }
Person.prototype.sayHello = function () { return `Hello ${this.name}`; };
const u1 = new Person("Alex", 25), u2 = new Person("John", 30);
console.log(u1); // Person { name: 'Alex', age: 25 }
console.log(u1.sayHello(), u1.sayHello === u2.sayHello); // Hello Alex true
console.log(Object.hasOwn(u1, "sayHello")); // false (it lives on the prototype)
class Student { constructor(name) { this.name = name; } }
console.log(typeof Student); // function
Student("x"); // TypeError: Class constructor Student cannot be invoked without 'new'
new P(); // ReferenceError: Cannot access 'P' before initialization
class P {}
The Four Pillars of OOP, with One Example Each
OOP organises code around objects such as User, Product and Order. Encapsulation keeps data and methods together and can hide data (a # field is truly private). Abstraction shows a simple interface and hides the steps, like a car's start button. Inheritance reuses a class with extends. Polymorphism lets one method name behave differently per class.
class Wallet {
#balance = 0; // encapsulation: private field
add(amount) { this.#balance += amount; return this.#balance; }
}
const w = new Wallet();
console.log(w.add(500), w.balance); // 500 undefined
class Animal { eat() { return "Eating"; } sound() { return "Animal sound"; } }
class Dog extends Animal { sound() { return "Bark"; } } // inheritance + override
class Cat extends Animal { sound() { return "Meow"; } }
for (const pet of [new Dog(), new Cat()]) console.log(pet.sound()); // Bark, then Meow (polymorphism)
console.log(new Dog().eat()); // Eating (inherited)
8. DOM, Events, BOM and Browser Storage
"Interactive" means the page reacts to clicks, typing and form submissions: menus open, a cart updates without reloading. JavaScript does this through the DOM (Document Object Model), the tree of objects the browser builds from the HTML. The BOM (Browser Object Model) is the browser around the page: window, location, navigator, history, screen. These snippets run in a browser, not Node.js.
// DOM: find, change, create
const heading = document.getElementById("title");
heading.textContent = "Welcome to WhosGeek";
const firstCard = document.querySelector(".card"); // first match or null
const allCards = document.querySelectorAll(".card"); // NodeList of all matches
const div = document.createElement("div");
document.body.appendChild(div);
// Events: run code when the user acts
const button = document.querySelector("#show-details");
button.addEventListener("click", () => {
document.querySelector("#details").style.display = "block";
});
// BOM
console.log(location.href); // the current URL
console.log(navigator.userAgent); // browser and OS details
alert("Welcome"); // same as window.alert, because window is the global object
Note the use of textContent: when the text comes from a user, prefer it over innerHTML, which would run any HTML inside it and opens the door to cross-site scripting (XSS) attacks.
localStorage, sessionStorage, Cookies and IndexedDB
| localStorage | sessionStorage | Cookies | IndexedDB | |
|---|---|---|---|---|
| Lifetime | Until removed | Until the tab closes | Until an expiry date, or the session | Until removed |
| Shared between tabs | Yes (same site) | No, each tab has its own | Yes | Yes |
| Sent to the server | No | No | Yes, with every request | No |
| Size (approx., browser-dependent) | About 5 MB | About 5 MB | About 4 KB each | Much larger |
| Stores | Strings only | Strings only | Strings | Objects, files, large data |
| Typical use | Theme, saved cart | One-tab form progress | Login sessions | Offline apps |
// Puzzle 11 (browser, or Node 24 with --experimental-webstorage --localstorage-file=store.db)
localStorage.setItem("count", 5);
console.log(localStorage.getItem("count") + 1);
localStorage.setItem("user", { name: "Karan" });
console.log(localStorage.getItem("user"));
Show answer
Output: 51, then [object Object]. Web storage converts everything to a string. The number 5 comes back as "5", and + 1 joins strings. The object is turned into the useless text "[object Object]". Store objects with JSON.stringify and read them with JSON.parse, and convert numbers with Number(). A missing key returns null, not undefined.
One security point that interviewers like: a cookie set by the server with the HttpOnly flag cannot be read by JavaScript at all, so a script injected through XSS cannot steal it. Anything in localStorage can be read by any script running on the page.
9. The Event Loop, Promises and async/await
JavaScript runs your code on one main thread. Slow work (timers, network, files) is handed to the environment, Web APIs in the browser or libuv in Node.js, and its callback waits in a queue. When the call stack is empty, the event loop moves the next callback onto it. Promise callbacks and code after an await go into the microtask queue; setTimeout callbacks go into the task queue (also called the callback queue). After each task, the whole microtask queue is emptied.
A promise stands for a result that arrives later: pending, then settled once as fulfilled or rejected. Promises flattened nested callbacks ("callback hell") into .then() chains, and async/await (ES2017) reads top to bottom. An async function always returns a promise, and await pauses only that function. For full explanations see Chapter 12 for the event loop and Chapter 13 for promises.
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
// Promise style
wait(100, { id: 7, name: "Karan" }).then((user) => console.log(user.name)); // Karan
// async/await style
async function showUser() {
const user = await wait(100, { id: 7, name: "Karan" });
console.log(`Welcome, ${user.name}`);
}
showUser();
console.log("Loading...");
// Loading...
// Karan
// Welcome, Karan
Karan's Puzzle, Solved
Back to Karan. His mistake was reading "delay 0" as "run next"; it really means "run as a task, after the script and all microtasks". He redoes the puzzle in three passes: synchronous lines, then microtasks until empty, then one task.
// Puzzle 12 (Karan's puzzle)
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
(async () => {
console.log("4");
await null;
console.log("5");
})();
console.log("6");
// 1 4 6 3 5 2
Pass one, synchronous: 1 prints; the timer goes to the task queue; the .then callback goes to the microtask queue; the async function runs synchronously up to its first await, so 4 prints, and the rest of it (console.log("5")) joins the microtask queue behind 3; then 6 prints. Pass two, microtasks in order: 3, 5. Pass three, the task: 2. The part people forget is that code before the first await is not asynchronous at all.
More Output Puzzles: Async
// Puzzle 13
new Promise((resolve) => {
console.log("A");
resolve();
console.log("B");
}).then(() => console.log("C"));
console.log("D");
Show answer
Output: A B D C. The function passed to new Promise (the executor) runs immediately and synchronously. Calling resolve() does not stop it, so B still prints. Only the .then callback is delayed to the microtask queue, so it runs after D.
// Puzzle 14
setTimeout(() => console.log("T1"), 0);
setTimeout(() => {
console.log("T2");
Promise.resolve().then(() => console.log("P-inside-T2"));
}, 0);
setTimeout(() => console.log("T3"), 0);
Promise.resolve().then(() => {
console.log("P1");
setTimeout(() => console.log("T-from-P1"), 0);
});
Show answer
Output: P1 T1 T2 P-inside-T2 T3 T-from-P1. The microtask P1 runs first and adds a fourth timer at the back of the task queue. Then each timer runs as its own task. After T2 finishes, the event loop empties the microtask queue, so P-inside-T2 runs before T3. The rule is "all microtasks after each task", not just "microtasks before timers".
// Puzzle 15 (Node.js only)
setTimeout(() => console.log("timeout"), 0);
Promise.resolve().then(() => console.log("promise"));
process.nextTick(() => console.log("nextTick"));
console.log("sync");
Show answer
Output: sync nextTick promise timeout. In Node.js, process.nextTick callbacks have their own queue that is drained before promise microtasks. The Node.js event loop post covers the phases in detail.
// Puzzle 16
async function getTotal() { return 499; }
console.log(getTotal());
Promise.resolve(1)
.then((x) => x + 1)
.then((x) => { throw new Error("boom " + x); })
.then(() => console.log("skipped"))
.catch((e) => { console.log(e.message); return 10; })
.then((x) => console.log("after catch", x))
.finally(() => console.log("finally"));
Show answer
Output: Promise { 499 }, then boom 2, after catch 10, finally. An async function wraps its return value in a promise, so you need await or .then to get 499. In the chain, a thrown error skips every .then until a .catch. Whatever .catch returns becomes a normal value again, so the chain continues with 10.
Interview Questions with Model Answers
Q: If JavaScript is single-threaded, how does it do several things at once? Model answer: "The language runs on one thread, but the environment does not. Timers and network work happen in the browser or in Node's libuv and the OS, and JavaScript runs their callbacks one at a time when the stack is empty."
Q: Promise.all, allSettled, race and any? Model answer: "all rejects as soon as one fails; allSettled never rejects and reports each status; race takes whichever settles first; any takes the first success and rejects only if all fail."
Spot the Bug
Each snippet below runs without a syntax error but gives the wrong result. Find the bug before you open the fix. All "wrong" outputs are real outputs from Node.js v24.
// Bug 1: the cart total is always 0
const wait = (ms, value) => new Promise((r) => setTimeout(() => r(value), ms));
const getPrice = (id) => wait(100, id * 100);
async function cartTotal(ids) {
let total = 0;
ids.forEach(async (id) => { total += await getPrice(id); });
return total;
}
cartTotal([1, 2, 3]).then(console.log); // 0
Show fix
forEach does not wait for async callbacks; it starts all three and returns at once, so total is still 0 when the function returns. Use Promise.all with map, which also fetches the prices in parallel:
async function cartTotal(ids) {
const prices = await Promise.all(ids.map(getPrice));
return prices.reduce((sum, p) => sum + p, 0);
}
cartTotal([1, 2, 3]).then(console.log); // 600
// Bug 2: the error escapes the try/catch
const failSoon = () => new Promise((_, reject) =>
setTimeout(() => reject(new Error("Payment gateway timeout")), 50));
async function pay() {
try {
return failSoon();
} catch (e) {
return "handled: " + e.message;
}
}
pay().catch((e) => console.log("escaped:", e.message)); // escaped: Payment gateway timeout
Show fix
return failSoon() hands the promise back without waiting for it, so the try block finishes before the rejection happens and the catch never sees it. Write return await failSoon(); inside a try. With that one word, pay() resolves to handled: Payment gateway timeout.
// Bug 3: user is undefined
function loadUser() {
return wait(10, 7)
.then((id) => { wait(10, { id, name: "Karan" }); })
.then((user) => user);
}
loadUser().then(console.log); // undefined
Show fix
The arrow function has curly braces, so it needs an explicit return; without one it returns undefined, and the next .then receives that. Either drop the braces, .then((id) => wait(10, { id, name: "Karan" })), or add return. Then the result is { id: 7, name: 'Karan' }.
// Bug 4: the dashboard takes twice as long as it should
async function loadDashboard() {
const user = await wait(300, "user");
const orders = await wait(300, "orders"); // does not depend on user
return [user, orders];
} // about 600 ms
Show fix
Each await waits for the previous one to finish, even though the two requests are independent. Start both together: const [user, orders] = await Promise.all([wait(300, "user"), wait(300, "orders")]);. In our test this took about 300 ms instead of 600 ms. Keep sequential await only when the second call needs the first result.
// Bug 5: every button alerts "Button 3"
var buttons = document.querySelectorAll("button"); // three buttons
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function () {
alert("Button " + i);
});
}
Show fix
This is Puzzle 2 in a real page. All three handlers close over the same var i, which is 3 by the time anyone clicks. Change var i to let i so each round has its own variable. In older code you will see an IIFE doing the same job, (function (i) { ... })(i); it works for the same reason.
One-Page Cheat Sheet
| Topic | Remember this |
|---|---|
| Scope | Global, function (var), block (let/const). Lookup walks outward; decided by where code is written. |
| Hoisting | var → undefined; let/const/class → TDZ ReferenceError; function declarations → fully usable. |
const | No reassignment; object contents can still change. |
| Empty values | undefined = not set; null = set to empty on purpose; undeclared = ReferenceError. typeof null is "object". |
| NaN | typeof NaN is "number"; NaN !== NaN; check with Number.isNaN(). |
| Equality | Use ===. "5" + 2 = "52", "5" - 2 = 3, null == undefined is true. |
| Strict mode | Undeclared assignment throws; classes and modules are always strict. |
| Arrow functions | No own this; don't use as object methods that need this. |
Lost this | const f = obj.method; f() loses obj. Fix with bind or an arrow wrapper. |
| Closure | Function + live link to outer variables. Used for privacy, counters, once, memoise, currying. |
| Loop + timer | var shares one variable (3 3 3); let makes one per round (0 1 2). |
| Strings | Immutable. slice allows negatives; substring swaps args and treats negatives as 0. |
| Arrays that mutate | push, pop, shift, unshift, splice, sort, reverse. |
| Array traps | forEach returns undefined; map(parseInt) gives NaNs; sort() sorts as text; give reduce a start value. |
| Collections | Map: any key type, ordered. Set: unique values. Weak versions: object keys only, not iterable, garbage-collectable. |
| Prototype/class | Methods live on the prototype and are shared. Class = sugar, but strict, needs new, and has a TDZ. |
| OOP pillars | Encapsulation (#private), abstraction, inheritance (extends), polymorphism (override). |
| DOM vs BOM | DOM = page tree (document); BOM = browser (window, location, navigator). |
| Storage | Web storage holds strings only; sessionStorage is per tab; cookies go to the server; IndexedDB for large data. |
| Event loop order | Sync code → (Node: nextTick) → all microtasks → one task → all microtasks → next task. |
| Promises | Executor runs synchronously; settles once; errors skip to .catch; async functions return promises. |
| await | Code before the first await is synchronous; use Promise.all for independent work; return await inside try. |
Common Mistakes (and the Fix)
| Mistake | What happens | Fix |
|---|---|---|
Using var in a loop with callbacks | Every callback sees the final value | Use let in the loop header |
| Arrow function as an object method | this.name is undefined (or empty in a browser) | Use method shorthand: greet() { ... } |
async callback inside forEach | The function returns before any await finishes | await Promise.all(items.map(...)) or a for...of loop |
Checking value === NaN | Always false | Number.isNaN(value) |
| Saving objects in localStorage directly | Stored as "[object Object]" | JSON.stringify to save, JSON.parse to read |
Assuming setTimeout(fn, 0) runs next | It runs after the script and every pending microtask | Order puzzles in three passes: sync, microtasks, tasks |
My Opinion
Predict before you run. Reading an explanation of the event loop feels like understanding, but only predicting output tests it. For every topic on this page, write your answer on paper first and run the code second; the gap between the two is exactly what you need to revise.
Learn the "why" in one sentence per puzzle. Interviewers rarely care that you know the output is undefined; they want the reason, such as "the local var is hoisted and shadows the global". If you cannot say the reason in one sentence, you will struggle with the follow-up question.
Default to const, then let, and treat var as read-only knowledge. Most scope puzzles exist because of var. You must be able to explain them, because older code bases and interviews still use them, but new code should not.
Make Promise.all a reflex for independent requests. Sequential await is the most common slow pattern in async code, and it is easy to spot in code review once you look for it.
Use the chapters for learning and this page for revision. Summaries of a topic you never learned properly turn into memorised answers that fall apart at the first follow-up question.
Try It Yourself
Answer on paper first, then check in Node.js or the browser console. Answers are hidden below.
1. What does this print?
console.log(typeof x, typeof y);
var x = 1;
let y = 2;
2. What does this print?
const nums = [1, 2, 3];
const r = nums.forEach((n) => n * 2);
console.log(r, nums.slice(-2));
3. What does this print?
function make() {
const fns = [];
for (var i = 0; i < 2; i++) fns.push(() => i);
return fns.map((f) => f());
}
console.log(make());
4. What does this print?
console.log("start");
setTimeout(() => console.log("timer"), 0);
Promise.resolve().then(() => console.log("micro 1")).then(() => console.log("micro 2"));
console.log("end");
5. What does this print?
const s = new Set(["a", "A", "a "]);
console.log(s.size);
6. Fix this so it prints Hello Karan:
const user = { name: "Karan", hi: () => "Hello " + this.name };
console.log(user.hi());
Show answers
1. ReferenceError: Cannot access 'y' before initialization
→ typeof x alone would be "undefined", but y is in the TDZ, and typeof does not protect you there
2. undefined [ 2, 3 ] → forEach always returns undefined
3. [ 2, 2 ] → one shared var i, which is 2 when the functions run; let gives [ 0, 1 ]
4. start end micro 1 micro 2 timer
→ micro 2 is queued when micro 1 finishes, still before the timer task
5. 3 → "a", "A" and "a " are three different strings
6. const user = { name: "Karan", hi() { return "Hello " + this.name; } };
Frequently Asked Questions
What is the difference between scope and closure?
Scope is the set of rules for where a name is visible, decided by where code is written. A closure is what you get when a function keeps using variables from an outer scope after that outer function has returned. Every closure depends on scope, but not every use of scope involves a closure.
Is setTimeout(fn, 0) really zero milliseconds?
No. Zero is the minimum delay, not a promise to run immediately. The callback waits until the current script and all microtasks finish, and browsers raise the delay to at least 4 ms for deeply nested timers.
Should I use .then() or async/await?
Both use promises underneath. async/await is easier to read and lets you use normal try/catch, so it is the usual choice for new code. .then() is still handy for short one-step chains, and you need to read it fluently because a lot of existing code uses it.
Are JavaScript classes real classes like in Java?
Not in the same way. A JavaScript class is built on prototypes: typeof a class is "function", and methods are stored on the prototype. The syntax looks familiar, but inheritance still works by prototype lookup.
Key Takeaways
varis function scoped and hoisted asundefined;letandconstare block scoped and throw in the Temporal Dead Zone.- A closure keeps a live link to outer variables, which explains both useful patterns (counters,
once, currying) and the classic loop bug. - Regular functions get
thisfrom the call; arrow functions borrow it from their surroundings. Extracting a method loses its object. - Use
===andNumber.isNaN(); remember thatforEachreturnsundefinedandsort()compares as text. - Map accepts any key type; Set removes exact duplicates; WeakMap and WeakSet hold objects only and let them be garbage collected.
- Web storage stores strings only; cookies travel to the server; sessionStorage is per tab.
- Event loop order: synchronous code, then all microtasks (promises, code after
await), then one task (setTimeout), repeated. - Use
Promise.allfor independent work, never put async callbacks inforEach, and writereturn awaitinsidetry.
Next, practise with the JavaScript Interview Questions and Answers guide, or go deeper into async with Chapter 13: Promises & Async Await.
References
- MDN Web Docs: Closures
- MDN Web Docs: The event loop
- MDN Web Docs: Map
- Node.js: The Event Loop, Timers, and process.nextTick()

0 Comments