Web Development chapters (5)
  1. 01HTML5 & Semantic Web Architecture
  2. 02CSS3 & Modern Styling Architecture
  3. 03Modern JavaScript (ES6+ & Asynchronous Engine)
  4. 04React.js Frontend Framework
  5. 05Backend Architecture with Node.js & Express

Chapter 03 · HTML, CSS, JS, React, Node

Modern JavaScript (ES6+ & Asynchronous Engine)

14 topics · 3 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

ES6+ introduced let/const, arrow functions, destructuring, modules and promises/async-await.

Understanding closures, prototypes, the DOM, the call stack, event loop and microtask queue explains how single-threaded JavaScript handles asynchronous work in the browser.

Output-order puzzles with setTimeout and promises, plus closures, hoisting and this, dominate JavaScript interviews.

API calls, UI event handling, timers and data transformation in every web app.

1

var vs let vs const & Hoisting

`var is function-scoped and hoisted (initialised to undefined). let and const are block-scoped and live in the temporal dead zone (TDZ) until their declaration runs; const` forbids reassignment (not mutation). Function declarations are hoisted completely.

In short: Prefer const, use let when you must reassign, avoid var.

Compare two ideas side by side

Think about it

Scope and hoisting are the most-asked JavaScript fundamentals and cause real production bugs.

Hoisting means declarations are registered at the start of the scope during the creation phase: `var x is hoisted and set to undefined, so reading it early yields undefined; let/const` are hoisted but not initialised, so reading early throws a ReferenceError (TDZ).

Function declarations are hoisted with their body, but function expressions assigned to `var are only undefined` until assignment.

`const arr = []; arr.

push(1) is allowed - the binding is constant, the object is not (use Object.

freeze` for shallow immutability).

Top-level `var becomes a property of window`, while let/const do not.

Classic bug: `var in a loop with setTimeout prints the final value because there is one shared binding; let` creates a fresh binding per iteration.

Key points

  • TDZ: Temporal Dead Zone: period between scope entry and let/const initialisation.
  • Hoisting: Declarations are registered before code runs (var -> undefined, function -> fully).
  • Block scope: Variable visible only inside the nearest { } block.

Example

Code
Hoisting and scope behaviour:
console.log(a);        // undefined (var hoisted)
var a = 1;
// console.log(b);   // ReferenceError (TDZ)
let b = 2;

hello();               // works: function declaration fully hoisted
function hello() { console.log("hi"); }
// bye();             // TypeError: bye is not a function (var is undefined)
var bye = function () {};

const list = [];
list.push(1);          // OK, mutation allowed
// list = [];         // TypeError: assignment to constant

for (var i = 0; i < 3; i++) setTimeout(() => console.log("var", i)); // 3 3 3
for (let j = 0; j < 3; j++) setTimeout(() => console.log("let", j)); // 0 1 2
2

Data Types & Strict Equality

JavaScript has 7 primitive types (string, number, bigint, boolean, undefined, null, symbol) and objects (arrays, functions, dates). === (strict equality) compares value and type; == (loose equality) coerces types first. Object.is handles NaN and -0.

In short: Use === always; know that null, undefined and NaN are special.

Variable → value in memory

Think about it

Type coercion and equality questions are interview staples and a common source of silent bugs.

Primitives are immutable and compared by value; objects are compared by reference ({} === {} is false).

typeof null is "object" (a historical bug); typeof [] is "object", so use `Array.

isArray`.

`NaN !

== NaN; use Number.

isNaN`.

Loose equality surprises: 0 == "" true, null == undefined true, "1" == 1 true, [] == false true.

Falsy values: false, 0, -0, 0n, "", null, undefined, NaN; everything else is truthy (including "0", [], {}).

Floating point: `0.1 + 0.2 !

== 0.3` due to IEEE-754 - compare with tolerance or use integers.

`??

only falls back for null/undefined while ||` falls back for any falsy value.

Use `Number.

MAX_SAFE_INTEGER` or BigInt for large integers.

Key points

  • Primitive: Immutable value type compared by value.
  • Type coercion: Automatic conversion of a value to another type by operators like ==, + .
  • Falsy: Value that converts to false in a boolean context.
  • Reference equality: Objects are equal only if they are the same object in memory.

Example

Code
Types, coercion and equality:
typeof 42;            // "number"
typeof null;          // "object"  (historic quirk)
Array.isArray([]);    // true

0 == "";              // true   (coercion)
0 === "";             // false
null == undefined;    // true
null === undefined;   // false
NaN === NaN;          // false
Number.isNaN(NaN);    // true
({}) === ({});        // false (different references)

0.1 + 0.2;            // 0.30000000000000004
Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON; // true

0 || "default";       // "default"
0 ?? "default";       // 0
3

Arrow Functions & Lexical this

Arrow functions ((a, b) => a + b) have concise syntax and do not have their own this, arguments, super or `prototype; they capture this` lexically from the enclosing scope. They cannot be used as constructors.

In short: Arrow functions use the this of the place where they were written.

Think about it

Losing this in callbacks is one of the most common JavaScript bugs.

For regular functions, this depends on how the function is called: method call (`obj.

fn()` -> obj), plain call (undefined in strict mode / global otherwise), new (new object), or explicit call/apply/bind.

Arrow functions ignore these rules, which makes them ideal for callbacks inside methods (timers, array methods, promise handlers) but wrong as object methods or event handlers that rely on this being the element.

A one-expression body returns implicitly; returning an object literal requires parentheses: () => ({ a: 1 }).

bind creates a permanently bound copy; call/apply invoke immediately with a chosen this.

Class fields with arrow functions give auto-bound methods (common in React class components).

Key points

  • Lexical this: this resolved from the surrounding scope at definition time.
  • bind / call / apply: Methods to set this explicitly (bind returns a new function).
  • Implicit return: Expression-bodied arrow returns its value without the return keyword.

Example

Code
Lexical this vs dynamic this:
const add = (a, b) => a + b;
const square = x => x * x;
const makeUser = name => ({ name });       // parentheses for object literal

const timer = {
  seconds: 0,
  startBad() {
    setInterval(function () { this.seconds++; }, 1000);  // this = window/undefined
  },
  start() {
    setInterval(() => { this.seconds++; }, 1000);        // this = timer (lexical)
  },
};

const counter = {
  n: 0,
  inc: () => { this.n++; },   // WRONG as a method: arrow ignores counter
  inc2() { this.n++; },       // correct
};
function greet(greeting) { return greeting + ", " + this.name; }
greet.call({ name: "Asha" }, "Hello");   // "Hello, Asha"
4

JavaScript Closures

A closure is a function bundled with the lexical environment in which it was created, so it keeps access to outer-scope variables even after the outer function has returned.

In short: An inner function remembers the variables around it.

Browser request flow

Think about it

Closures are the most asked advanced JS concept and the basis for private data and many patterns. A backpack: the function carries the supplies (variables) from the place it was created wherever it goes.

Every function creation captures a reference to its scope chain, not a copy of values.

Closures enable private state (module pattern), factories, memoisation, currying, debouncing/throttling and event handlers that "remember" data.

Because variables are captured by reference, loops with `var share one variable (the classic bug) while let` gives one binding per iteration.

Closures can cause memory leaks if they unintentionally hold large objects or DOM nodes - release references when done.

React hooks rely on closures, and stale closures occur when a callback captures an old state value.

Key points

  • Lexical environment: Record of variables in a scope plus a link to the outer scope.
  • Currying: Transforming f(a, b) into f(a)(b) using closures.
  • Memoisation: Caching results of pure functions in a closed-over object.

Example

Code
Private state, currying, memoise, debounce:
function makeCounter() {
  let count = 0;                       // private: only reachable via the closure
  return {
    inc: () => ++count,
    reset: () => { count = 0; },
    value: () => count,
  };
}
const c1 = makeCounter();
c1.inc(); c1.inc();
console.log(c1.value());               // 2

const multiplyBy = n => x => x * n;    // currying
const double = multiplyBy(2);
double(21);                            // 42

function memoize(fn) {
  const cache = new Map();
  return n => cache.has(n) ? cache.get(n) : (cache.set(n, fn(n)), cache.get(n));
}

function debounce(fn, ms) {
  let t;
  return (...args) => { clearTimeout(t); t = setTimeout(() => fn(...args), ms); };
}
5

Destructuring & Spread Operator

Destructuring unpacks array elements and object properties into variables. Spread (...) expands iterables or objects in place; rest (...) collects the remaining items into an array or object.

In short: Pull values out in one line; copy or merge with spread.

Operator types at a glance

Think about it

Used in virtually every React and Node codebase and in everyday data handling.

Object destructuring supports renaming ({ a: x }), defaults ({ a = 1 }), nesting and computed keys; array destructuring is positional and can skip elements ([, second]) or swap variables ([a, b] = [b, a]).

Function parameters can be destructured, which gives named-argument style APIs.

Spread creates shallow copies: nested objects are still shared, so use structuredClone for deep copies.

Later properties overwrite earlier ones in `{ ...

a, ...

b }`.

Rest must be last.

Optional chaining `?.

and nullish coalescing ??

` avoid noisy null checks.

Immutable update patterns in React rely on spread.

Key points

  • Shallow copy: Copies top level only; nested references are shared.
  • Rest parameter: Collects remaining arguments/elements into an array.
  • ??: Returns right side only when left is null or undefined (unlike ||).

Example

Code
Destructuring, spread and rest:
const user = { name: "Asha", age: 21, address: { city: "Pune" } };
const { name, age = 18, address: { city }, role = "student" } = user;
const { name: userName } = user;                 // rename

const [first, , third, ...others] = [10, 20, 30, 40, 50];
let a = 1, b = 2; [a, b] = [b, a];                // swap

const updated = { ...user, age: 22 };            // copy + override
const merged = [...[1, 2], ...[3, 4]];           // [1,2,3,4]
const deep = structuredClone(user);              // deep copy

const total = (...nums) => nums.reduce((s, n) => s + n, 0);
function connect({ host = "localhost", port = 3000 } = {}) { return host + ":" + port; }

const zip = user.address?.zip ?? "N/A";
6

Array map, filter, reduce

Array higher-order methods transform data declaratively: map returns a new array by transforming each element, filter keeps elements for which the callback is truthy, and reduce folds the array into a single accumulated value. Others: find, some, every, flatMap, sort.

In short: map changes every item, filter keeps some items, reduce boils everything down to one value.

Think about it

The most common JavaScript coding-round tasks use these three methods.

map/filter/reduce do not mutate the original array and can be chained.

reduce(callback, initial) should always get an initial value - without it an empty array throws and the first element is used as the accumulator.

Callbacks receive (item, index, array).

reduce can build objects (group by, count).

forEach returns undefined, so it cannot be chained.

sort mutates and by default sorts as strings (`[10, 2, 1].

sort() -> [1, 10, 2]) - pass a comparator (a, b) => a - b; newer toSorted()` is non-mutating.

Complexity is O(n) per pass; chaining many passes on huge arrays can be replaced by a single reduce or loop.

Key points

  • Higher-order function: Function that takes or returns another function.
  • Accumulator: Running value carried between reduce steps.
  • Pure transformation: Returns a new value without modifying inputs.

Example

Code
map, filter and reduce:
const nums = [1, 2, 3, 4, 5, 6];
const doubled = nums.map(n => n * 2);                    // [2,4,6,8,10,12]
const evens   = nums.filter(n => n % 2 === 0);           // [2,4,6]
const sum     = nums.reduce((acc, n) => acc + n, 0);     // 21

const result = nums.filter(n => n % 2 === 0).map(n => n ** 2).reduce((a, n) => a + n, 0); // 56

const people = [{ n: "A", city: "Pune" }, { n: "B", city: "Delhi" }, { n: "C", city: "Pune" }];
const byCity = people.reduce((acc, p) => {
  (acc[p.city] ??= []).push(p.n);
  return acc;
}, {});                                                   // { Pune: ["A","C"], Delhi: ["B"] }

[10, 2, 1].sort();                 // [1, 10, 2]  (string sort!)
[10, 2, 1].sort((a, b) => a - b);  // [1, 2, 10]
7

Prototypes & Prototypal Inheritance

Every JavaScript object has an internal link [[Prototype]] (accessible via Object.getPrototypeOf or __proto__) to another object. Property lookup walks this prototype chain until found or until null. Constructor functions and ES6 class are syntactic layers over this mechanism.

In short: If an object does not have a property, JavaScript asks its prototype, then that prototype, and so on.

Inheritance: child gets parent traits

Think about it

Interviewers ask how inheritance works in JavaScript and the difference from class-based languages.

Functions have a prototype property used as the [[Prototype]] of objects created with new.

Methods placed on the prototype are shared by all instances (saves memory) while properties set in the constructor are per instance.

`Object.

create(proto)` creates an object with a chosen prototype.

class A extends B sets `A.prototype.

__proto__ = B.prototype; super` calls the parent.

instanceof checks the chain; hasOwnProperty / `Object.

hasOwn` check own properties only.

Arrays, functions and dates inherit from `Array.

prototype, Function.

prototype`, ...

, finally `Object.

prototype`.

Do not modify built-in prototypes (monkey patching), and prefer composition over deep inheritance.

Key points

  • Prototype chain: Linked series of objects searched during property lookup.
  • [[Prototype]]: Hidden link from an object to its prototype.
  • Own property: Property defined directly on the object, not inherited.

Example

Code
Prototype chain, classes and Object.create:
function Animal(name) { this.name = name; }
Animal.prototype.speak = function () { return this.name + " makes a sound"; };

class Dog extends Animal {
  speak() { return super.speak() + " (woof)"; }
}
const d = new Dog("Rex");
d.speak();                                   // "Rex makes a sound (woof)"

Object.getPrototypeOf(d) === Dog.prototype;  // true
d instanceof Animal;                         // true
Object.hasOwn(d, "speak");                   // false (inherited)

const base = { greet() { return "hi " + this.name; } };
const kid = Object.create(base);
kid.name = "Mia";
kid.greet();                                 // "hi Mia"
8

DOM Manipulation APIs

The Document Object Model is a tree of objects representing the page. JavaScript selects nodes (querySelector, getElementById), reads and changes content (textContent, innerHTML), attributes and classes (setAttribute, classList, dataset), styles, and creates or removes nodes (createElement, append, remove).

In short: Find an element, change it, add it, or remove it from the page with JavaScript.

Page structure + style

Think about it

Core of browser scripting; the basis of what frameworks like React automate.

querySelector returns the first match (static NodeList from querySelectorAll); getElementsBy* returns live collections.

Prefer textContent for user text - innerHTML parses HTML and is an XSS risk with untrusted input.

`classList.

add/remove/toggle` changes styling via CSS.

Reading layout properties (offsetHeight) after writes forces synchronous reflow ("layout thrashing") - batch reads then writes.

Build many nodes in a DocumentFragment or use insertAdjacentHTML once.

requestAnimationFrame schedules visual updates before the next paint.

Run DOM code after parsing using `defer or the DOMContentLoaded` event.

Key points

  • NodeList (static vs live): querySelectorAll is static; getElementsBy* collections update automatically.
  • Reflow: Browser recalculating layout after geometry changes.
  • XSS: Cross-site scripting - injected malicious script, often via innerHTML.
  • DocumentFragment: Off-DOM container used to batch node insertion.

Example

Code
Creating and updating elements:
const list = document.querySelector("#todo-list");
const input = document.querySelector("#new-todo");

function addTodo(text) {
  const li = document.createElement("li");
  li.textContent = text;                   // safe: no HTML parsing
  li.classList.add("todo");
  li.dataset.id = crypto.randomUUID();
  const del = document.createElement("button");
  del.textContent = "Delete";
  del.setAttribute("aria-label", "Delete " + text);
  li.append(del);
  list.append(li);
}

const frag = document.createDocumentFragment();
for (let i = 0; i < 100; i++) {
  const li = document.createElement("li");
  li.textContent = "Item " + i;
  frag.append(li);
}
list.append(frag);                         // one DOM write

document.querySelector(".banner")?.remove();
document.title = "Updated";
9

Event Delegation & Bubbling

DOM events travel in three phases: capturing (root to target), target, then bubbling (target back up to root). Event delegation attaches one listener to a common ancestor and uses event.target (or closest) to handle events from many descendants.

In short: Instead of a listener on every button, put one on the parent and check who was clicked.

Think about it

Efficient handling of dynamic lists and a very common interview question.

Most events bubble (focus/blur do not; use focusin/focusout).

`event.

target is the element that triggered the event; event.

currentTarget` is the element the listener is attached to.

Use `target.

closest(".

item")` to handle clicks on inner children of a row.

Delegation reduces memory, works for elements added later, and simplifies cleanup.

stopPropagation() halts propagation (use sparingly - it breaks analytics and delegation); preventDefault() cancels the browser default action (form submit, link navigation).

Listener options: { capture, once, passive }; passive: true improves scroll performance.

Remove listeners with the same function reference, or use an `AbortController` signal.

Key points

  • Bubbling: Event propagates from the target up through its ancestors.
  • target vs currentTarget: target = origin of the event; currentTarget = element holding the listener.
  • preventDefault: Cancels the default browser action but not propagation.

Read more

Example

Code
Delegated click handling:
const list = document.querySelector("#todo-list");

list.addEventListener("click", (e) => {
  const btn = e.target.closest("button.delete");
  if (btn && list.contains(btn)) {
    btn.closest("li").remove();
    return;
  }
  const item = e.target.closest("li");
  if (item) item.classList.toggle("done");
});                                           // works for items added later too

document.querySelector("form").addEventListener("submit", (e) => {
  e.preventDefault();                          // stop page reload
  const data = Object.fromEntries(new FormData(e.currentTarget));
  console.log(data);
});

const ac = new AbortController();
window.addEventListener("resize", onResize, { signal: ac.signal, passive: true });
// ac.abort();  // removes the listener
10

JavaScript Event Loop

JavaScript runs on a single thread with a call stack. Web APIs handle timers and network and push callbacks to queues. The event loop moves tasks to the stack only when it is empty; the microtask queue (promise reactions, queueMicrotask) is drained completely before the next macrotask (setTimeout, I/O, UI events).

In short: Synchronous code first, then promises, then timers.

CALL STACK (LIFO) fn3() [Top Frame] fn2() main() / global WEB APIs / BROWSER DOM, setTimeout, fetch() Thread Pool Execution EVENT LOOP ↻ Microtask Queue (VIP): Promise.then, queueMicrotask (Drained First!) Macrotask Queue: setTimeout, setInterval, I/O callbacks
Modern JavaScript (ES6+ & Asynchronous Engine)

Think about it

Output-order puzzles are the most common advanced JS question and explain UI freezes.

Cycle: run the current script/task -> drain all microtasks (including newly queued ones) -> render if needed (browser) -> next macrotask.

setTimeout(fn, 0) is a macrotask, so it runs after pending promise callbacks (and has a minimum delay of about 1-4 ms).

Long synchronous loops block rendering and input because nothing else can run; break work into chunks or use Web Workers.

`await x` schedules the continuation as a microtask.

Microtask starvation: an endlessly re-queued microtask freezes the page.

requestAnimationFrame callbacks run before painting.

In Node the phases are timers, pending, poll, check (setImmediate) and close, with `process.

nextTick` running before promises.

Key points

  • Call stack: LIFO structure of currently executing functions.
  • Microtask: High-priority job (promise reaction) run before the next macrotask.
  • Macrotask: setTimeout, setInterval, I/O, UI event callbacks.
  • Web API: Browser-provided async facility (timers, fetch, DOM events) outside the JS engine.

Example

Code
Event-loop order and chunking:
console.log("1 sync");
setTimeout(() => console.log("4 timeout"), 0);
Promise.resolve().then(() => console.log("3 microtask"));
console.log("2 sync");
// Output: 1 sync, 2 sync, 3 microtask, 4 timeout

// Blocking the loop:
// const end = Date.now() + 3000; while (Date.now() < end) {}  // UI frozen for 3s

// Chunking long work
function processInChunks(items, fn) {
  let i = 0;
  (function next() {
    const end = performance.now() + 8;
    while (i < items.length && performance.now() < end) fn(items[i++]);
    if (i < items.length) setTimeout(next);   // yield to the event loop
  })();
}
11

JavaScript Promises

A Promise represents the eventual result of an asynchronous operation and is in one of three states: pending, fulfilled or rejected. .then(onFulfilled), .catch(onRejected) and .finally() register handlers and each returns a new promise, allowing chaining.

In short: A Promise is a receipt for a result that will arrive later.

Think about it

Promises underpin every API call and are heavily tested, along with chaining semantics.

Handlers always run asynchronously as microtasks.

A value returned from `.

then is passed to the next .

then; a returned promise is awaited; a thrown error skips to the next .

catch`.

Create promises with `new Promise((resolve, reject) => ...

)` (the executor runs synchronously).

Combinators: `Promise.

all (parallel, rejects on first failure), Promise.

allSettled (waits for all, never rejects), Promise.

race (first to settle), Promise.

any` (first to fulfil).

Always handle rejections - unhandled ones raise unhandledrejection.

Promises are eager (start immediately) and cannot be cancelled; use `AbortController` for fetch.

Convert callbacks to promises (promisify) to escape callback hell.

Key points

  • Settled: Promise is either fulfilled or rejected (no longer pending).
  • Chaining: Each then returns a new promise so steps run in sequence.
  • Callback hell: Deeply nested callbacks that promises/async-await flatten.

Example

Code
Creating, chaining and combining promises:
const wait = (ms, value) => new Promise(resolve => setTimeout(() => resolve(value), ms));

wait(100, 1)
  .then(v => v + 1)                 // 2
  .then(v => wait(100, v * 10))     // returns a promise -> awaited
  .then(v => { throw new Error("boom " + v); })
  .catch(err => { console.error(err.message); return "recovered"; })
  .finally(() => console.log("cleanup"));

Promise.all([wait(100, "a"), wait(200, "b")]).then(console.log);       // ["a","b"]
Promise.allSettled([wait(1, "ok"), Promise.reject("no")])
  .then(r => console.log(r.map(x => x.status)));                      // ["fulfilled","rejected"]
Promise.race([wait(500, "slow"), wait(50, "fast")]).then(console.log); // "fast"

function timeout(p, ms) {
  return Promise.race([p, new Promise((_, rej) => setTimeout(() => rej(new Error("timeout")), ms))]);
}
12

async / await Syntax

async functions always return a promise. Inside them await pauses the function until the awaited promise settles and returns its value (or throws its rejection), allowing synchronous-looking code with try/catch/finally.

In short: Write asynchronous code in a top-to-bottom style; await means "wait here for the result".

Think about it

The standard modern way to write async code; error handling and parallelism pitfalls are interview staples.

Code before the first await runs synchronously; the rest is queued as a microtask continuation.

await only pauses its own async function, not the whole program.

Awaiting in a loop runs steps sequentially; for parallel work start all promises first and `await Promise.

all(...

)`.

Forgetting await leaves you with a pending promise instead of a value.

return await inside try/catch is needed to catch rejections of the returned promise.

`for await...

of` consumes async iterables.

Top-level await is allowed in ES modules.

A common mistake is `array.

forEach(async ...

) - forEach does not wait; use for...

of or Promise.

all(map(...

))`.

Key points

  • async function: Function that implicitly returns a Promise.
  • Sequential vs parallel await: Awaiting one by one vs starting all then awaiting together.
  • Top-level await: await usable directly in a module scope.

Example

Code
async/await with error handling:
async function loadUser(id) {
  try {
    const res = await fetch("/api/users/" + id);
    if (!res.ok) throw new Error("HTTP " + res.status);
    return await res.json();
  } catch (err) {
    console.error("Failed:", err.message);
    return null;
  } finally {
    hideSpinner();
  }
}

// sequential (slow): total = t1 + t2
const a = await loadUser(1);
const b = await loadUser(2);

// parallel (fast): total = max(t1, t2)
const [x, y] = await Promise.all([loadUser(1), loadUser(2)]);

// forEach does NOT await
for (const id of ids) { await save(id); }                  // sequential
await Promise.all(ids.map(id => save(id)));                 // parallel
13

Fetch API & Network Requests

fetch(url, options) returns a promise that resolves to a Response object. It supports methods, headers, bodies (JSON, FormData), credentials, caching and cancellation with AbortController. Body readers such as res.json(), res.text() and res.blob() also return promises.

In short: fetch asks a server for data and gives you a promise of the response.

Think about it

Every data-driven web app talks to APIs; mishandled errors and CORS are the common problems.

fetch only rejects on network failure; HTTP errors such as 404 or 500 still resolve, so check `res.

ok or res.

status`.

Send JSON with method: "POST", headers: { "Content-Type": "application/json" } and `body: JSON.

stringify(data)`.

A response body can be consumed once (clone it if needed).

Cross-origin requests are governed by CORS; the server must send `Access-Control-Allow-Origin, and non-simple requests trigger a preflight OPTIONS`.

Cookies are sent cross-origin only with credentials: "include".

Use AbortController for cancellation and timeouts, and `AbortSignal.

timeout(ms)`.

Handle loading, error and empty states in the UI, and retry with backoff for transient failures.

Key points

  • Response.ok: True when status is 200-299.
  • CORS: Browser policy controlling cross-origin requests via server headers.
  • Preflight: OPTIONS request the browser sends before certain cross-origin requests.
  • AbortController: Object used to cancel fetch requests.

Example

Code
GET, POST and cancellation with fetch:
async function getJSON(url, { signal } = {}) {
  const res = await fetch(url, { signal, headers: { Accept: "application/json" } });
  if (!res.ok) throw new Error("HTTP " + res.status + " " + res.statusText);
  return res.json();
}

async function createPost(post) {
  const res = await fetch("/api/posts", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(post),
    credentials: "same-origin",
  });
  if (!res.ok) throw new Error(await res.text());
  return res.json();
}

const controller = new AbortController();
getJSON("/api/slow", { signal: controller.signal }).catch(e => {
  if (e.name === "AbortError") console.log("cancelled");
});
setTimeout(() => controller.abort(), 3000);
14

ES Modules & Bundling

ES modules (import / export) split code into files with their own scope and explicit dependencies. They are static (analysable at build time), strict by default, evaluated once and loaded in browsers with <script type="module">. Bundlers (Vite, webpack, esbuild, Rollup) combine, transform and optimise modules for production.

In short: Split code into files, export what is needed, import where used; a bundler packs it for the browser.

Modules plug into your program

Think about it

Module systems and bundling are fundamental to every modern front-end and Node project and to performance work.

Named exports (`export const a) are imported with braces and the same name; the default export (export default) is imported under any name; import * as ns` collects everything.

Imports are live read-only bindings, not copies.

Static structure enables tree shaking (removing unused exports).

Dynamic `import(".

/x.

js")` returns a promise and enables code splitting and lazy loading.

CommonJS (require/`module.

exports`) is synchronous and used by older Node code; interop needs care.

Bundlers also handle minification, transpiling (Babel/SWC), asset imports, source maps and hashing for caching.

Circular imports can yield undefined values at evaluation time - restructure instead.

Key points

  • Tree shaking: Bundler removes unused exports from the output.
  • Code splitting: Dividing the bundle into chunks loaded on demand.
  • Live binding: Imported names reflect later changes to the exported variable.
  • CommonJS: Node original module system using require and module.exports.

Example

Code
Named, default and dynamic imports:
// math.js
export const PI = 3.14159;
export function sum(a, b) { return a + b; }
export default function mul(a, b) { return a * b; }

// app.js
import mul, { sum, PI as pi } from "./math.js";
import * as math from "./math.js";

// lazy-load a heavy chart library only when needed
button.addEventListener("click", async () => {
  const { renderChart } = await import("./chart.js");
  renderChart(data);
});

// index.html
// <script type="module" src="/app.js"></script>

// package.json (Node ES modules)
// { "type": "module" }

Solved examples

Example 01 · Basic

Use destructuring and spread to create a copy of { id: 1, tags: ["a"], meta: { v: 1 } } with id changed to 2. Is meta shared?

Given Data:
    Required To Find:

    New object and sharing behaviour

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: const copy = { ...orig, id: 2 }
    Step 2: Spread copies top-level properties only
    Step 3: copy.meta === orig.meta (same reference)
    Final Answer: copy = { id: 2, tags: ["a"], meta: { v: 1 } }; meta and tags are shared (shallow copy). Use structuredClone for a deep copy.

    Approach note: Shallow vs deep copy is a standard follow-up.

    Example 02 · Intermediate

    Predict the output: console.log("A"); setTimeout(() => console.log("B"), 0); Promise.resolve().then(() => console.log("C")); (async () => { console.log("D"); await null; console.log("E"); })(); console.log("F");

    Given Data:
      Required To Find:

      Order of logs

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: Sync: A, then D (async body runs synchronously until first await), then F
      Step 2: Microtasks in order queued: C (then), E (continuation after await)
      Step 3: Macrotask: B
      Final Answer: A, D, F, C, E, B

      Approach note: Code before the first await is synchronous; the rest becomes a microtask.

      Example 03 · Advanced

      Fetch three URLs in parallel and tolerate individual failures.

      Given Data:
        Required To Find:

        Code

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: Map urls to fetch promises
        Step 2: Use Promise.allSettled to wait for all
        Step 3: Filter fulfilled results
        Final Answer: const results = await Promise.allSettled(urls.map(u => fetch(u).then(r => r.json()))); const data = results.filter(r => r.status === "fulfilled").map(r => r.value);

        Approach note: Promise.all would reject on the first failure and lose the others.

        Example 04 · Basic

        Given [{ name: "A", price: 100, qty: 2 }, { name: "B", price: 50, qty: 0 }, { name: "C", price: 20, qty: 5 }], compute the total value of items that are in stock.

        Given Data:
          Required To Find:

          Total

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: filter(i => i.qty > 0) removes B
          Step 2: map(i => i.price * i.qty) gives [200, 100]
          Step 3: reduce((s, v) => s + v, 0) adds them
          Final Answer: 300

          Approach note: Chain filter -> map -> reduce and always pass the initial value to reduce.

          Example 05 · Intermediate

          A list of 1000 <li> items is rendered dynamically and each needs a click handler that removes it. What is the better design?

          Given Data:
            Required To Find:

            Design and code

            Formula Applied:—
            Step-by-Step Solution:
            Step 1: Attach ONE click listener on the <ul>
            Step 2: Use e.target.closest("button.delete") to find the clicked control
            Step 3: Remove its closest("li")
            Step 4: Newly added items work automatically
            Final Answer: ul.addEventListener("click", e => { const btn = e.target.closest("button.delete"); if (btn) btn.closest("li").remove(); });

            Approach note: One listener instead of 1000 saves memory and handles dynamic content.

            Example 06 · Intermediate

            In a browser script (non-module), what do these print? const o = { n: 1, a: () => this.n, b() { return this.n; } }; console.log(o.b(), o.a());

            Given Data:
              Required To Find:

              Output

              Formula Applied:—
              Step-by-Step Solution:
              Step 1: o.b() is a method call, so this = o and it returns 1
              Step 2: The arrow function a has no own this; it uses the this of the surrounding scope
              Step 3: At the top level of a classic script that is window, and window.n is undefined
              Step 4: So o.a() returns undefined
              Final Answer: 1 undefined

              Approach note: Never use arrow functions as object methods that rely on this.

              Real-world applications

              Web

              Using Modern JavaScript (ES6+) & Asynchronous Engine in real projects

              API calls, UI event handling, timers and data transformation in every web app.

              Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

              Common mistakes

              ❌ Myth: const makes objects immutable.

              Why this is wrong: const only prevents reassigning the binding.

              ✅ Verified Truth: Use Object.freeze (shallow) or immutable patterns to prevent mutation.

              ⚠️ Exam Tip: Say "constant binding, not constant value".

              ❌ Myth: setTimeout(fn, 0) runs immediately.

              Why this is wrong: It schedules a macrotask that runs after the current stack and all microtasks.

              ✅ Verified Truth: Promises run before zero-delay timers.

              ⚠️ Exam Tip: Always list sync -> microtask -> macrotask.

              ❌ Myth: JavaScript is multi-threaded because it is asynchronous.

              Why this is wrong: Your code runs on one thread; the runtime/Web APIs do the waiting concurrently.

              ✅ Verified Truth: Asynchrony is achieved via the event loop, not parallel JS execution (Workers are separate).

              ⚠️ Exam Tip: Explain single thread + event loop.

              ❌ Myth: == and === differ only slightly so it does not matter.

              Why this is wrong: Loose equality applies surprising coercion rules ([] == false, "0" == false).

              ✅ Verified Truth: Use === by default and convert types explicitly.

              ⚠️ Exam Tip: Give two surprising == examples.

              ❌ Myth: fetch rejects on HTTP 404 or 500.

              Why this is wrong: fetch only rejects on network errors; HTTP error statuses resolve normally.

              ✅ Verified Truth: Check res.ok and throw manually.

              ⚠️ Exam Tip: Mention res.ok in every fetch answer.

              ❌ Myth: forEach with async callbacks waits for each call.

              Why this is wrong: forEach ignores the returned promises and finishes immediately.

              ✅ Verified Truth: Use for...of with await or Promise.all(map(...)).

              ⚠️ Exam Tip: Mention sequential vs parallel.

              ❌ Myth: Closures copy the variables they capture.

              Why this is wrong: They keep a live reference to the variables, so later changes are visible.

              ✅ Verified Truth: That is why the var-in-loop bug occurs.

              ⚠️ Exam Tip: Explain with the setTimeout loop example.

              Revision notes

              ES6+ introduced let/const, arrow functions, destructuring, modules and promises/async-await. Understanding closures, prototypes, the DOM, the call stack, event loop and microtask queue explains how single-threaded JavaScript handles asynchronous work in the browser.

              High-Yield Quick Revision Points

              1. var function-scope hoisted undefined; let/const block-scope with TDZ
              2. always ===; typeof null is object; NaN !== NaN; 0.1+0.2 float error
              3. arrow: lexical this, no arguments/prototype, not for methods
              4. closure = function + remembered scope (by reference)
              5. destructuring, spread = shallow copy, rest collects
              6. map transforms, filter selects, reduce folds (pass initial value)
              7. prototype chain lookup; class is sugar over prototypes
              8. textContent safe, innerHTML XSS risk; batch DOM writes
              9. delegation: one listener, target.closest, bubbling
              10. sync -> microtask -> macrotask; never block the loop
              11. Promise states pending/fulfilled/rejected; all vs allSettled vs race
              12. await in loop = sequential; Promise.all = parallel
              13. fetch: check res.ok; CORS; AbortController
              14. ES modules: named/default/dynamic import, tree shaking, bundlers

              Practice questions

              Question 1 · MCQ (Interview / semester)

              Which declaration is in the temporal dead zone before it is declared?

              Question 2 · MCQ (Interview / semester)

              Output of: setTimeout(()=>log(1),0); Promise.resolve().then(()=>log(2)); log(3);

              Question 3 · MCQ (Interview / semester)

              Which method waits for all promises and never rejects?

              Question 4 · MCQ (Interview / semester)

              Arrow functions differ from normal functions because they:

              Question 5 · MCQ (Interview / semester)

              What is the value of typeof null?

              Question 6 · MCQ (Interview / semester)

              What does [1, 2, 3].reduce((a, n) => a + n, 10) return?

              Question 7 · MCQ (Interview / semester)

              In event delegation, which property identifies the clicked inner element?

              Question 8 · MCQ (Interview / semester)

              Where does property lookup go when a property is not found on an object?

              Question 9 · MCQ (Interview / semester)

              What does fetch do on an HTTP 500 response?

              Question 10 · MCQ (Interview / semester)

              Which import form loads a module lazily?