SyntaxPilot
Courses/JavaScript/Lesson 40
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

JavaScript · Lesson 40 of 40

Interview questions and the road to React and Node backends

queued

These are the notes for JavaScript episode 40, the last episode of the course. The first half is the five questions interviewers love because the obvious answer is wrong: var vs let in a loop with setTimeout, the event loop order, losing this, shallow vs deep copy (spread vs structuredClone), and writing debounce from scratch. For each one we predict, run it for real, and explain the reason in one line. The second half is the road ahead: UI as a function of state (the idea behind React, in plain JavaScript), a real HTTP server with node:http called with fetch from the same program, and a roadmap. Every output below is real Node.js output (Node 24, node main.js).

Builds on: closures (episode 10), spread (12), this (17), JSON (19), the event loop, promises and timers (24), async/await (27), TypeScript (32), and everything in the capstone (39). Leads to: the new series JavaScript Coding Questions: real interview problems, three per episode, each solved live with the obvious attempt first.

The problem: the interview room

Your first interview for a JavaScript developer job. The interviewer writes three lines on the whiteboard and asks one question: "What does this print?"

It looks easy. You give the quick answer, and the interviewer smiles, because the quick answer is wrong. These questions are chosen because the obvious answer fails. What gets you the job is explaining why. So for every question below:

  1. Predict the output out loud.
  2. Run it for real.
  3. Explain the reason in one line, and give the fix.

Q1: var in a loop with setTimeout

Three seats in a cinema. The loop goes from 1 to 3, and for each seat a timer prints the seat number a moment later.

for (var i = 1; i <= 3; i++) {
  setTimeout(() => console.log("seat", i), 0);
}

The quick answer is seat 1, seat 2, seat 3. The real output:

seat 4
seat 4
seat 4

Three times, and there isn't even a seat 4!

Why: the timers run later, after the loop has completely finished. And var makes only one i for the whole loop. By the time the timers run, that one i has already counted up to 4 (the value that made i <= 3 false and stopped the loop). All three callbacks read the same box.

The fix is one word: change var to let.

for (let i = 1; i <= 3; i++) {
  setTimeout(() => console.log("seat", i), 0);
}

Output:

seat 1
seat 2
seat 3

let makes a fresh i for every round of the loop, and each callback remembers its own one. That's a closure (episode 10): a function remembers the variables around it where it was created.

One box, or one box per round

Think of one whiteboard in a classroom. With var there is one box: the number is rubbed out and rewritten, 1 → 2 → 3 → 4. Three timers look at the same box later, and all see 4. With let, every round gets its own little box: timer 1 keeps box 1, timer 2 keeps box 2.

How many i boxes? What the timers see
var i one, for the whole function all read the final value, 4
let i a new one each round each reads its own: 1, 2, 3

The line to say in the interview: "var is function-scoped; let and const are block-scoped, and with let each loop round is its own block. The callback runs after the loop ends, so with var it sees the final value."

Block scope, shown directly

if (true) {
  var a = 1;
  let b = 2;
}
console.log(a);
console.log(b);

Output:

1
/tmp/notes40/scope.js:6
console.log(b);
            ^

ReferenceError: b is not defined

var a leaks out of the if block (it belongs to the whole function or file). let b exists only inside the { }.

Fixing it without let (older code)

Before let existed (2015), people gave each timer its own copy another way:

for (var i = 1; i <= 3; i++) {
  ((seat) => setTimeout(() => console.log("seat", seat), 0))(i);
}
for (var j = 1; j <= 3; j++) {
  setTimeout((seat) => console.log("chair", seat), 0, j);
}

Output:

seat 1
seat 2
seat 3
chair 1
chair 2
chair 3
  • The first loop uses an IIFE (an immediately invoked function expression): the function is called at once with the current i, so its parameter seat is a new box each round.
  • The second passes j as an extra argument to setTimeout: everything after the delay is handed to the callback when it runs, and the value is read now, not later.

Q2: the event loop order

From episode 24. A restaurant order: print 1, a zero-millisecond timer prints 2, a promise prints 3, and print 4.

console.log("1 order placed");
setTimeout(() => console.log("2 timer"), 0);
Promise.resolve().then(() => console.log("3 promise"));
console.log("4 bill printed");

The quick answer is 1, 2, 3, 4, top to bottom: the timer is zero milliseconds, so surely it's instant. The real output:

1 order placed
4 bill printed
3 promise
2 timer

1, 4, 3, 2. The bill printed before the timer and the promise, and the promise beat the timer.

One waiter, three lists

In the restaurant In JavaScript In this example
One waiter serves everybody JavaScript runs on one thread one thing at a time
He always finishes the table in front of him first the call stack: normal (synchronous) code runs to the end lines 1 and 4
When free, he checks the VIP list first, every time the microtask queue: promise .then callbacks, code after await 3
Only then does he take the next one from the normal waiting line the task queue (macrotask queue): setTimeout, setInterval, I/O 2

Zero milliseconds means "as soon as possible", not "now". A timer callback can only run when the call stack is empty and all microtasks are done.

The rule: synchronous code first, then all microtasks, then one task, then all microtasks again, and so on.

A harder one, with async/await

console.log("start");
setTimeout(() => console.log("timeout"), 0);
(async () => {
  console.log("async start");
  await null;
  console.log("after await");
})();
Promise.resolve().then(() => console.log("then"));
console.log("end");

Output:

start
async start
end
after await
then
timeout
  • An async function runs synchronously until its first await, so async start prints straight after start.
  • Everything after await is a microtask. It was queued before the .then callback, so after await comes first.
  • The timer is last, as always.

Q3: losing this

A shop object with a name and a greet method. Call it directly, and also pass it to setTimeout.

const shop = {
  name: "Sharma Sweets",
  greet() {
    console.log("Welcome to " + this.name);
  },
};
shop.greet();
setTimeout(shop.greet, 0);

The quick answer is "Welcome to Sharma Sweets" twice. The real output:

Welcome to Sharma Sweets
Welcome to undefined

Why: this is decided by how a function is called, not where it was written (episode 17). In shop.greet() the dot says "this is shop". But setTimeout(shop.greet, 0) receives only the function, without the shop in front of it. Later it is called on its own, so this is not the shop any more. (In Node, a timer callback is called with this set to the timer's own Timeout object, which has no name, so you get undefined. In a browser, this would be window and you would see "Welcome to " with an empty name. Either way: wrong.)

Two fixes:

const shop = {
  name: "Sharma Sweets",
  greet() {
    console.log("Welcome to " + this.name);
  },
};
shop.greet();
setTimeout(() => shop.greet(), 0);
setTimeout(shop.greet.bind(shop), 0);

Output:

Welcome to Sharma Sweets
Welcome to Sharma Sweets
Welcome to Sharma Sweets
  • Arrow wrapper: () => shop.greet() calls the method with the dot, so this is shop again.
  • bind: shop.greet.bind(shop) makes a new function with this locked to shop, whoever calls it later.

Like a delivery boy handed a parcel with no address: bind writes the address on the parcel.

In a class, it crashes instead

Class bodies always run in strict mode, so a method called on its own gets this = undefined, and reading a property of undefined is an error:

class Counter {
  n = 0;
  inc() {
    this.n++;
    return this.n;
  }
}
const c = new Counter();
console.log(c.inc());
const f = c.inc;
f();

Output:

1
/tmp/notes40/e2.js:4
    this.n++;
    ^

TypeError: Cannot read properties of undefined (reading 'n')

The fix is the same: bind.

class Counter {
  n = 0;
  inc() {
    this.n++;
    return this.n;
  }
}
const c = new Counter();
const f = c.inc.bind(c);
console.log(f(), f());

Output:

1 2

The opposite trap: an arrow function as a method

const shop = {
  name: "Sharma Sweets",
  greet: () => console.log("Welcome to " + this.name),
};
shop.greet();

Output:

Welcome to undefined

Arrow functions have no this of their own: they use the this of the code around them (here, the module, not shop). Even shop.greet() with the dot can't change that. Use the method shorthand greet() { ... } for methods, and arrows for callbacks inside them.

Q4: shallow vs deep copy

A restaurant order for table 4, with a list of items. Copy it with spread (episode 12), change the copy, then print the original.

const order = { table: 4, items: ["dosa"] };
const copy = { ...order };
copy.table = 7;
copy.items.push("vada");
console.log(order);

The quick answer: the original is untouched, table 4 and just dosa. The real output:

{ table: 4, items: [ 'dosa', 'vada' ] }

Table 4 is safe, but the original now has a vada too. Somebody's bill just changed.

Why: spread copies only the top shelf. table is a plain number (a primitive), so its value was copied. But items is an array, an object, and the copy got only a reference to the same array: the same address in memory. Like two people sharing one shopping bag: push into one, and both see it. This is a shallow copy.

The fix is a deep copy: structuredClone, built into Node (17+) and every modern browser. It copies every level.

const order = { table: 4, items: ["dosa"] };
const copy = structuredClone(order);
copy.table = 7;
copy.items.push("vada");
console.log(order);
console.log(copy);

Output:

{ table: 4, items: [ 'dosa' ] }
{ table: 7, items: [ 'dosa', 'vada' ] }

Now the original keeps only its dosa, and the copy has table 7 with dosa and vada.

The catch: functions can't be cloned

structuredClone({ f(){} });

Output (first lines):

node:internal/worker/js_transferable:127
  const serializedData = nativeStructuredClone(value, idlOptions);
                         ^

DOMException [DataCloneError]: f(){} could not be cloned.

The error is a DOMException whose name is DataCloneError, and the message quotes the function's source text exactly as you wrote it. Caught and printed by name:

try {
  structuredClone({ dish: "dosa", f() {} });
} catch (err) {
  console.log(err.name + ": " + err.message);
}

Output:

DataCloneError: f() {} could not be cloned.

structuredClone copies data: objects, arrays, numbers, strings, Date, Map, Set, RegExp, typed arrays, and even circular references. It does not copy functions, DOM nodes, or class identity (a cloned class instance comes back as a plain object).

Why not JSON.parse(JSON.stringify(x))?

That old trick is also a deep copy, but it loses anything JSON can't hold:

const order = { table: 4, at: new Date(0), note: undefined, tags: new Set(["veg"]) };
const a = JSON.parse(JSON.stringify(order));
const b = structuredClone(order);
console.log(a);
console.log(b);
console.log(b.at instanceof Date, b.tags.has("veg"));

Output:

{ table: 4, at: '1970-01-01T00:00:00.000Z', tags: {} }
{
  table: 4,
  at: 1970-01-01T00:00:00.000Z,
  note: undefined,
  tags: Set(1) { 'veg' }
}
true true

With JSON: the Date became a string, note: undefined disappeared, and the Set became an empty object. structuredClone kept all three.

Way to copy Depth Nested objects/arrays Functions Date, Map, Set
{ ...obj }, Object.assign({}, obj), [...arr] shallow shared (same reference) kept (shared) shared
JSON.parse(JSON.stringify(obj)) deep copied dropped broken
structuredClone(obj) deep copied DataCloneError copied correctly

Q5: write debounce

This question is different: write the code.

The lift door

In a food delivery app, you type paneer into the search box. If every key press sends a search to the server, that's a request for p, for pa, for pan, and so on: wasted work and a slow app. Think of a lift door: it waits a few seconds before closing, and if someone else walks in, it starts waiting all over again. The search should wait too, and run only once you stop typing for a moment. That's called debounce.

First, the obvious way

let calls = 0;
const search = (text) => console.log(`search #${++calls}: ${text}`);
for (const text of ["p", "pa", "pan", "pane", "paneer"]) search(text);

Output:

search #1: p
search #2: pa
search #3: pan
search #4: pane
search #5: paneer

Five searches for one word. Imagine a thousand users doing this at once.

Now, debounce

function debounce(fn, ms) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), ms);
  };
}
let calls = 0;
const search = debounce((text) => console.log(`search #${++calls}: ${text}`), 300);
["p", "pa", "pan", "pane", "paneer"].forEach((text, i) => {
  setTimeout(() => search(text), i * 100);
});

The letters are "typed" 100 ms apart, like a real person. Output:

search #1: paneer

One search, for paneer. Each key came before the 300 ms were up, so each one reset the timer. Only the last one survived.

How it works, line by line:

  • debounce(fn, ms) takes a function and a waiting time and returns a new function.
  • let timer lives in a closure: every call of the returned function shares the same timer.
  • clearTimeout(timer) cancels the previous wait (the lift door starts again). Calling clearTimeout(undefined) the first time is harmless.
  • setTimeout(() => fn(...args), ms) starts a new wait; ...args (rest parameters) collects whatever arguments were passed, and fn(...args) (spread) passes them on.

Five lines of code, and closures, rest parameters and timers all in one answer.

How to answer any output question

  1. Read it aloud: what runs now, and what runs later?
  2. Find the trap: var, timers, promises, this, copies.
  3. Say your answer, then the reason in one line. The reason matters more than the answer.
  4. Give the fix: let, an arrow, bind, structuredClone.
  5. Not sure? Say so, and say exactly what you would run to check. Interviewers like that honesty much more than a confident guess.

Common mistakes (with the real messages)

Mistake Code What you see Why Fix
using a let variable before its line console.log(x); let x = 1; ReferenceError: Cannot access 'x' before initialization let is hoisted but not ready yet (the temporal dead zone) declare before use
using a block variable outside its block if (true) { let b = 2; } console.log(b); ReferenceError: b is not defined let/const are block-scoped declare it in the outer scope
var in a loop with a callback for (var i ...) setTimeout(() => log(i)) seat 4 three times one shared i let i
taking a class method out and calling it alone const f = obj.method; f(); TypeError: Cannot read properties of undefined (reading 'n') the class method lost its this obj.method.bind(obj) or () => obj.method()
passing an object method to setTimeout setTimeout(shop.greet, 0) Welcome to undefined called without the dot arrow wrapper or bind
arrow function as an object method greet: () => this.name Welcome to undefined arrows have no own this method shorthand greet() {}
expecting spread to copy nested data { ...order } then copy.items.push(...) the original changes too shallow copy shares nested objects structuredClone
cloning an object with a function structuredClone({ f(){} }) DOMException [DataCloneError]: f(){} could not be cloned. functions can't be cloned clone only data
deep copy with JSON JSON.parse(JSON.stringify(x)) Date becomes a string, Set becomes {}, undefined vanishes JSON has no such types structuredClone
thinking setTimeout(fn, 0) is instant setTimeout(fn, 0) runs after sync code and promises timers wait in the task queue use the event loop order
debounce without clearTimeout return () => setTimeout(fn, ms) every call still runs, just later the old timers are never cancelled clearTimeout(timer) first

(Run for real: the let line prints ReferenceError: Cannot access 'x' before initialization.)

The road ahead, part 1: React's big idea, in plain JavaScript

The restaurant menu board

At the restaurant In React
The owner's list of today's dishes and prices (the data) state: { items: [...] }
The menu board, drawn from that list a component: a function, state in → screen out
Prices change: you change the list and redraw the board re-render: new state → new UI

You don't scratch out numbers on the board. You change the list and redraw. In React you change the state, and React redraws the screen for you.

The same idea, no library

function Cart({ items }) {
  const total = items.reduce((sum, i) => sum + i.price, 0);
  const rows = items.map((i) => `<li>${i.dish}</li>`).join("");
  return `<ul>${rows}</ul><p>Total: Rs ${total}</p>`;
}
let state = { items: [{ dish: "dosa", price: 60 }] };
console.log(Cart(state));
state = { items: [...state.items, { dish: "idli", price: 40 }] };
console.log(Cart(state));

Output:

<ul><li>dosa</li></ul><p>Total: Rs 60</p>
<ul><li>dosa</li><li>idli</li></ul><p>Total: Rs 100</p>
  • Cart is a component: a function that takes the data (destructured { items }, like React's "props"), adds up the total with reduce, builds a row per dish with map, and returns the HTML for the screen.
  • The new state is made with spread, adding an idli without changing the old state (immutability). React compares old and new state to know what changed, so it expects new objects, not edited ones.
  • Two screens: one dosa and ₹60, then dosa and idli, ₹100.

That's the heart of React: UI is a function of state, UI = f(state). React adds JSX, so you write the HTML directly inside JavaScript (<li>{i.dish}</li>), and it updates only the parts of the page that actually changed. Everything else is the JavaScript you already know: map, reduce, spread, destructuring, arrow functions.

The road ahead, part 2: a real web server with node:http

Every app's data comes from a server: a program that waits for requests and sends back responses, like a restaurant's kitchen window. Node has one built in: node:http.

const http = require("node:http");
const menu = [{ dish: "dosa", price: 60 }, { dish: "idli", price: 40 }];
const server = http.createServer((req, res) => {
  if (req.url === "/menu") {
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify(menu));
  } else {
    res.writeHead(404);
    res.end("not found");
  }
});
server.listen(3000, async () => {
  console.log("server on port 3000");
  const r1 = await fetch("http://localhost:3000/menu");
  console.log(r1.status, await r1.json());
  const r2 = await fetch("http://localhost:3000/pizza");
  console.log(r2.status, await r2.text());
  server.close();
});

Output:

server on port 3000
200 [ { dish: 'dosa', price: 60 }, { dish: 'idli', price: 40 } ]
404 not found
  • http.createServer(handler) gets a function that runs for every request. req is the request (its url, method, headers); res is the response you build.
  • For /menu: res.writeHead(200, ...) sends status code 200 (OK) and a header saying the body is JSON; res.end(JSON.stringify(menu)) sends the menu as text (episode 19) and finishes the response.
  • Anything else gets 404 (not found).
  • server.listen(3000, callback) starts the server on port 3000, a numbered door on this computer. The callback runs once it's ready.
  • In the same program we act as the customer (the client): fetch sends a request; r1.status is the status code; await r1.json() reads the body and parses it from JSON; await r2.text() reads it as plain text (async/await, episode 27).
  • server.close() stops listening so the program can end. Without it, Node keeps running, waiting for more requests.

A real web server and a real client, in nineteen lines. (Port 3000 must be free; if another program uses it the server emits an error like Error: listen EADDRINUSE: address already in use 0.0.0.0:3000; the address part depends on the machine.)

The same server with Express

Frameworks like Express make this shorter, with routes like app.get("/menu", ...). Installed with npm install express (version 5.3.0 here):

const express = require("express");
const app = express();
const menu = [{ dish: "dosa", price: 60 }, { dish: "idli", price: 40 }];
app.get("/menu", (req, res) => res.json(menu));
const server = app.listen(3001, async () => {
  const r1 = await fetch("http://localhost:3001/menu");
  console.log(r1.status, await r1.json());
  const r2 = await fetch("http://localhost:3001/pizza");
  console.log(r2.status, r2.headers.get("content-type"));
  server.close();
});

Output:

200 [ { dish: 'dosa', price: 60 }, { dish: 'idli', price: 40 } ]
404 text/html; charset=utf-8

res.json(menu) sets the status, the JSON header and the body in one call, and Express answers unknown routes with a 404 page by itself. Underneath it's exactly the same thing: a request comes in, and you send a response.

Your roadmap from here

  1. HTML, CSS and the DOM: so your JavaScript can control a real web page.
  2. React: components, state, hooks (front end).
  3. Node with Express: routes and REST APIs (back end).
  4. A database: SQL (such as PostgreSQL) or MongoDB, to save your data.
  5. TypeScript (episode 32): use it every day.
  6. Build and deploy two or three real projects and put them online. Projects get interviews much more than certificates.
  7. Practise questions: exactly what the next series on this channel is for.

Mini project: a live dish search (debounce + server + component)

Everything from today in one program: a node:http server with a /search?q= route, a component that turns state into a screen, and a debounced fetch, so typing paneer sends one request instead of six.

const http = require("node:http");
const menu = [
  { dish: "paneer tikka", price: 180 },
  { dish: "palak paneer", price: 160 },
  { dish: "masala dosa", price: 70 },
  { dish: "idli", price: 40 },
];

// 1. the server: GET /search?q=... answers with matching dishes as JSON
let requests = 0;
const server = http.createServer((req, res) => {
  const url = new URL(req.url, "http://localhost");
  if (url.pathname === "/search") {
    requests++;
    const q = (url.searchParams.get("q") || "").toLowerCase();
    const found = menu.filter((m) => m.dish.includes(q));
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify(found));
  } else {
    res.writeHead(404);
    res.end("not found");
  }
});

// 2. the screen: a component, UI = f(state)
function Results({ query, items }) {
  if (items.length === 0) return `No dishes match "${query}"`;
  return items.map((i) => `- ${i.dish}: Rs ${i.price}`).join("\n");
}

// 3. debounce, exactly as in the episode
function debounce(fn, ms) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), ms);
  };
}

// 4. the client: typing calls a debounced fetch
let state = { query: "", items: [] };
const search = debounce(async (query) => {
  const r = await fetch("http://localhost:3000/search?q=" + encodeURIComponent(query));
  state = { query, items: await r.json() };
  console.log(`[${r.status}] results for "${query}":`);
  console.log(Results(state));
  if (query === "paneer") search("pizza");
  else {
    console.log("requests sent to the server:", requests);
    server.close();
  }
}, 300);

server.listen(3000, () => {
  ["p", "pa", "pan", "pane", "panee", "paneer"].forEach((text, i) => {
    setTimeout(() => search(text), i * 100);
  });
});

Output:

[200] results for "paneer":
- paneer tikka: Rs 180
- palak paneer: Rs 160
[200] results for "pizza":
No dishes match "pizza"
requests sent to the server: 2
  • new URL(req.url, "http://localhost") splits /search?q=paneer into pathname (/search) and searchParams (q = paneer). req.url is only the path, so a base address is needed.
  • encodeURIComponent makes the text safe inside a URL (spaces become %20).
  • Six keystrokes, one request; then a second search for pizza shows the empty-results screen. Two requests in total.

Try next: add a price filter (/search?q=paneer&max=170), or show Searching... as a state before the response arrives.

Practice

1. Homework: write throttle, the cousin of debounce, allowing at most one call every 300 ms.

Debounce waits until the calls stop; throttle lets a call through at most once per time window while the calls keep coming (useful for scroll and resize events, where you want regular updates, not just one at the end).

Solution
function throttle(fn, ms) {
  let last = -Infinity;
  return (...args) => {
    const now = Date.now();
    if (now - last >= ms) {
      last = now;
      fn(...args);
    }
  };
}
let calls = 0;
const onScroll = throttle((n) => console.log(`update #${++calls}: scroll event ${n}`), 300);
for (let n = 1; n <= 15; n++) {
  setTimeout(() => onScroll(n), (n - 1) * 70);
}

Output:

update #1: scroll event 1
update #2: scroll event 6
update #3: scroll event 11

Fifteen scroll events, 70 ms apart (0 to 980 ms). The first runs at once; the next allowed one must be at least 300 ms later: event 6 (350 ms), then event 11 (700 ms). The next window would open at 1000 ms, but the last event was at 980 ms, so only three updates. last lives in a closure, just like timer in debounce; starting at -Infinity means the very first call always passes.

(The same 15 events through debounce(..., 300) would give only one call, for event 15.)

2. Homework: add a /price?dish=dosa route to the server.

Solution
const http = require("node:http");
const menu = [{ dish: "dosa", price: 60 }, { dish: "idli", price: 40 }];
const server = http.createServer((req, res) => {
  const url = new URL(req.url, "http://localhost");
  if (url.pathname === "/menu") {
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify(menu));
  } else if (url.pathname === "/price") {
    const dish = url.searchParams.get("dish");
    const item = menu.find((m) => m.dish === dish);
    if (!dish) {
      res.writeHead(400);
      res.end("say which dish: /price?dish=dosa");
    } else if (item) {
      res.writeHead(200, { "Content-Type": "application/json" });
      res.end(JSON.stringify({ dish, price: item.price }));
    } else {
      res.writeHead(404);
      res.end(`no dish called ${dish}`);
    }
  } else {
    res.writeHead(404);
    res.end("not found");
  }
});
server.listen(3000, async () => {
  for (const path of ["/price?dish=dosa", "/price?dish=pizza", "/price"]) {
    const r = await fetch("http://localhost:3000" + path);
    console.log(path, "->", r.status, await r.text());
  }
  server.close();
});

Output:

/price?dish=dosa -> 200 {"dish":"dosa","price":60}
/price?dish=pizza -> 404 no dish called pizza
/price -> 400 say which dish: /price?dish=dosa
  • Compare url.pathname, not req.url: req.url is /price?dish=dosa, so req.url === "/price" would never be true.
  • searchParams.get("dish") returns null when the parameter is missing, so the route answers 400 (Bad Request: the client asked wrongly) instead of crashing.
  • An unknown dish is 404: the request was fine, but the thing doesn't exist.

3. Homework: make Cart show a message when the list is empty.

Solution
function Cart({ items }) {
  if (items.length === 0) return "<p>Your cart is empty</p>";
  const total = items.reduce((sum, i) => sum + i.price, 0);
  const rows = items.map((i) => `<li>${i.dish}</li>`).join("");
  return `<ul>${rows}</ul><p>Total: Rs ${total}</p>`;
}
let state = { items: [] };
console.log(Cart(state));
state = { items: [...state.items, { dish: "dosa", price: 60 }] };
console.log(Cart(state));
state = { items: state.items.filter((i) => i.dish !== "dosa") };
console.log(Cart(state));

Output:

<p>Your cart is empty</p>
<ul><li>dosa</li></ul><p>Total: Rs 60</p>
<p>Your cart is empty</p>

An early return handles the special case first. Removing an item uses filter, which makes a new array, so the old state is never changed. In React you would write the same check as if (items.length === 0) return <p>Your cart is empty</p>;.

4. Homework: explain each of today's answers in one line, out loud.

Model answers
  • Q1: "var gives one shared i that is 4 when the timers run; let gives each round its own i."
  • Q2: "Synchronous code first, then microtasks like promises, then tasks like timers: 1, 4, 3, 2."
  • Q3: "this depends on how a function is called; setTimeout calls it without the object, so use an arrow or bind."
  • Q4: "Spread is a shallow copy, so the nested array is shared; structuredClone makes a deep copy."
  • Q5: "Debounce keeps one timer in a closure and resets it on every call, so only the last call runs."

5. Predict the output, then run it (from the async section above).

console.log("start");
setTimeout(() => console.log("timeout"), 0);
(async () => {
  console.log("async start");
  await null;
  console.log("after await");
})();
Promise.resolve().then(() => console.log("then"));
console.log("end");
Solution
start
async start
end
after await
then
timeout

The async function body runs synchronously until await; the rest of it is a microtask queued before the .then; the timer waits in the task queue.

6. Fix the var loop without changing var to let.

Solution

See "Fixing it without let" above: wrap the body in an IIFE that takes i as a parameter, or pass i as the third argument of setTimeout. Both print 1, 2, 3.

Quick quiz

What does it print?

setTimeout(() => console.log("A"), 0);
Promise.resolve().then(() => console.log("B"));
for (var i = 0; i < 2; i++) {}
console.log("C" + i);

A. A B C2 B. C2 B A C. C1 A B D. C2 A B

Answer

B: C2, then B, then A. Node really prints:

C2
B
A

Normal code runs first: after the loop, the one shared var i is 2 (the value that made i < 2 false), so it prints C2. Then the microtask queue: the promise prints B. Then the task queue: the timer prints A. (With let i, the last line would throw ReferenceError: i is not defined, because i would exist only inside the loop.)

Interview questions

  1. What is the difference between var, let and const? var is function-scoped, can be redeclared, and is hoisted with the value undefined. let and const are block-scoped, can't be redeclared in the same scope, and are hoisted but not usable before their line (the temporal dead zone, giving ReferenceError: Cannot access 'x' before initialization). const also can't be reassigned (but an object it points to can still be changed).
  2. Why does var in a loop with setTimeout print the last value? There's one i for the whole loop, the callbacks run after the loop ends, and they all read that one variable. let creates a new binding per iteration.
  3. Explain the event loop. JavaScript runs one thing at a time on the call stack. When the stack is empty, it runs all microtasks (promise callbacks, code after await, queueMicrotask), then one task from the task queue (timers, I/O, events), then microtasks again, and repeats.
  4. Is setTimeout(fn, 0) instant? No. It means "run in the task queue as soon as possible": after the current synchronous code and all pending microtasks. The delay is a minimum, not a promise.
  5. Microtask vs macrotask? Microtasks (promises) are drained completely before the next macrotask (timer, I/O). That's why a resolved promise's .then beats a zero-ms timer.
  6. How is this decided? By how the function is called: obj.method() → obj; a plain call f() → undefined in strict mode (or the global object in sloppy mode); new F() → the new object; call/apply/bind → whatever you pass. Arrow functions don't have their own this; they use the surrounding one.
  7. bind vs call vs apply? call(thisArg, a, b) and apply(thisArg, [a, b]) call the function now with that this; bind(thisArg) returns a new function with this fixed, to call later.
  8. Shallow copy vs deep copy? A shallow copy ({...obj}, Object.assign, [...arr], slice) copies only the top level; nested objects are shared by reference. A deep copy (structuredClone) copies every level, so changes to the copy never reach the original.
  9. Limits of structuredClone? It throws DataCloneError for functions (and DOM nodes), and class instances lose their class (they come back as plain objects). It does handle Date, Map, Set, RegExp and circular references.
  10. Why not always use JSON.parse(JSON.stringify(x))? It turns Date into strings, drops undefined and functions, turns Map/Set into {}, and throws on circular references.
  11. Write debounce. Where would you use it? Keep one timer in a closure; on every call, clearTimeout it and start a new one. Use it for search boxes, auto-save, and window resize handlers where you only want the final value.
  12. Debounce vs throttle? Debounce runs once after the calls stop for a while. Throttle runs at most once per time window while calls continue (scroll position, button spam, game input).
  13. What does "UI is a function of state" mean? The screen is computed from data: UI = f(state). To change the screen you change the state and re-render, instead of editing the page by hand. React components are functions that do exactly this.
  14. Why should state be updated immutably in React? React decides what to redraw by comparing old and new state by reference. If you mutate the same object (items.push), the reference doesn't change and React may not re-render. Create new objects/arrays with spread, map or filter.
  15. What is an HTTP server, and what happens in a request? A program listening on a port. A client sends a request (method like GET, a URL path, headers, maybe a body); the server's handler runs and sends a response (a status code, headers, a body).
  16. What do the status codes 200, 400, 404 and 500 mean? 200 OK; 400 Bad Request (the client sent something invalid); 404 Not Found; 500 Internal Server Error (the server broke).
  17. What is a REST API? A style of web API where URLs name resources (/menu, /orders/7) and HTTP methods say what to do (GET read, POST create, PUT/PATCH update, DELETE remove), usually sending JSON.
  18. What does Express add over node:http? Routing (app.get("/menu", ...)), helpers like res.json, middleware (logging, parsing JSON bodies, authentication), and automatic 404 handling. Underneath it still uses node:http.

Glossary

Term Meaning Example
output question an interview question asking what code prints "what does this print?"
scope the part of the code where a variable exists inside { } or a function
function scope the variable belongs to the whole function var i
block scope the variable belongs only to the nearest { } let i, const x
hoisting declarations are processed before the code runs var x is undefined before its line
temporal dead zone (TDZ) the time before a let/const line, when using it throws Cannot access 'x' before initialization
closure a function that remembers the variables from where it was created each timer remembers its own i; debounce's timer
IIFE a function called immediately where it's written ((seat) => ...)(i)
callback a function you pass to be called later () => console.log("seat", i)
setTimeout run a function after at least some milliseconds, via the task queue setTimeout(fn, 0)
clearTimeout cancel a timer that hasn't run yet clearTimeout(timer)
single thread JavaScript does one thing at a time the one waiter
synchronous code code that runs straight through, now console.log("1 order placed")
asynchronous code code that runs later timers, promises, fetch
call stack where the currently running functions are tracked; normal code runs here first lines 1 and 4 in Q2
event loop the mechanism that moves waiting callbacks onto the call stack when it's empty stack → microtasks → task
microtask queue the "VIP list": promise callbacks and code after await, all run before the next task .then(() => ...)
task queue (macrotask queue) the normal waiting line: timers, I/O, events the setTimeout callback
promise an object for a value that will be ready later Promise.resolve()
async / await write promise code that reads top to bottom; await pauses the function await fetch(...)
this the object a function was called on, decided at call time shop in shop.greet()
method a function stored on an object greet() { ... }
strict mode a stricter JavaScript mode (always on in classes and ES modules); plain calls get this = undefined class Counter { ... }
arrow function a short function with no own this () => shop.greet()
bind make a new function with this fixed shop.greet.bind(shop)
call / apply call a function now with a chosen this greet.call(shop)
primitive a simple value copied by value: number, string, boolean, null, undefined, bigint, symbol table: 4
reference the address of an object; copying it shares the same object copy.items === order.items
shallow copy a copy of the top level only; nested objects are shared { ...order }
deep copy a copy of every level; nothing is shared structuredClone(order)
spread ... expand an object's properties or an array's items into a new one [...state.items, idli]
rest parameters collect all arguments into an array (...args) =>
structuredClone built-in deep copy for data structuredClone(order)
DataCloneError the error when something can't be cloned f(){} could not be cloned.
DOMException the web-standard error type structuredClone throws DOMException [DataCloneError]
debounce run a function only after calls have stopped for a set time one search for "paneer"
throttle run a function at most once per time window one scroll update per 300 ms
state the data a screen is drawn from { items: [{ dish: "dosa", price: 60 }] }
component a function that turns state (props) into UI Cart({ items })
props the data passed into a component { items }
render / re-render draw the UI from state / draw it again after state changes console.log(Cart(state)) twice
immutability never changing old data; making a new copy instead state = { items: [...state.items, x] }
React a JavaScript library for building UIs from components and state UI = f(state)
JSX HTML-like syntax inside JavaScript, used by React <li>{i.dish}</li>
hooks React functions for state and effects inside components useState, useEffect
DOM the browser's live tree of the page that JavaScript can change document.querySelector
front end / back end the part running in the user's browser / the part running on a server React / Node
HTTP the protocol browsers and servers use to talk GET /menu
HTTP server a program that listens for HTTP requests and sends responses http.createServer(...)
client the program that sends requests fetch(...) in the same file
request (req) what the client asks for: method, URL, headers, body req.url === "/menu"
response (res) what the server sends back: status, headers, body res.end("not found")
route a URL path the server answers in a particular way /menu, /price
query string the ?key=value part of a URL ?dish=dosa
URL / searchParams built-in parser for addresses and their query string url.searchParams.get("dish")
header extra information sent with a request or response Content-Type: application/json
status code a number saying how the request went 200 OK, 400 Bad Request, 404 Not Found, 500 Server Error
port a numbered door on a computer that a server listens on 3000
localhost this same computer http://localhost:3000
node:http Node's built-in HTTP module require("node:http")
JSON a text format for data JSON.stringify(menu)
fetch send an HTTP request and get a promise of the response (built into Node 18+ and browsers) await fetch(url)
res.json() / .text() (fetch) read a response body as parsed JSON / as text await r1.json()
Express a popular Node web framework with routing and middleware app.get("/menu", ...)
middleware Express functions that run on each request before the route express.json()
npm Node's package manager, used to install libraries npm install express
REST API URLs as resources + HTTP methods as actions, usually with JSON GET /menu, POST /orders
database a program that stores data permanently PostgreSQL, MongoDB
SQL the language for relational (table) databases SELECT * FROM menu
MongoDB a popular document database that stores JSON-like objects { dish: "dosa" }
TypeScript JavaScript with types, checked before running episode 32
deploy put your app online for others to use a live URL

Summary

  • Predict, run, explain: the reason in one line matters more than the answer.
  • var vs let: var shares one i (seat 4, three times); let gives a new i each round (1, 2, 3).
  • Event loop: synchronous code, then all microtasks (promises), then tasks (timers): 1, 4, 3, 2. Zero ms is not instant.
  • this depends on how a function is called; passing a method as a callback loses it. Fix with an arrow wrapper or bind.
  • Spread is shallow (nested arrays are shared); structuredClone is deep, but can't clone functions (DataCloneError).
  • Debounce resets one timer on every call, so only the last call runs; throttle allows one call per window.
  • React's idea: UI is a function of state. Change the state immutably, re-render.
  • A Node server: http.createServer turns a request into a response with a status code; fetch is the client; Express makes it shorter.
  • Roadmap: HTML/CSS/DOM → React → Node + Express → a database → TypeScript every day → build and deploy real projects → practise questions.
  • Next on SyntaxPilot: the new series JavaScript Coding Questions, real interview problems solved live, starting with episode 1.