Find a subject or note

13 results found

JavaScriptArray Methods, Loop Mechanics & The Async Trap

Mastering slice vs splice, search & reduce patterns, loop intent (for...in vs for...of vs map), and the async forEach trap.

JavaScriptasync / await & Modern Asynchronous Flow

Mastering async functions, the non-blocking await keyword, error handling with try/catch, and avoiding performance waterfalls.

JavaScriptcall(), apply(), bind() (Controlling this)

How to explicitly control function execution context in JavaScript using call, apply, and bind.

JavaScriptErrors, try/catch & Defensive Design

Understanding built-in error types, the Error object, custom error classes, async handling, and defensive validation patterns.

JavaScriptThe Event Loop

How JavaScript coordinates synchronous code, the Call Stack, Microtask Queue, and Macrotask Queue.

JavaScriptFetch API, HTTP & Web APIs

HTTP fundamentals, URLSearchParams, response handling, CORS, AbortController, and production service layers.

JavaScriptFirst-Class Functions, Callbacks & Closures

How first-class functions, callbacks, and closures connect to form the foundation of modern JavaScript.

JavaScriptObject Utilities (keys, values, entries, fromEntries)

How Object.keys, Object.values, Object.entries, and Object.fromEntries bridge objects and arrays in JavaScript.

JavaScriptPromises & Promise Combinators

Understanding asynchronous execution, Promise lifecycles, error propagation, and Promise combinators (all, allSettled, race, any).

JavaScriptReturn, Scope & Hoisting in Functions

How return statements, lexical scope, and hoisting determine how functions execute in JavaScript.

JavaScriptSecurity Basics: XSS & Safe DOM Rendering

Cross-Site Scripting (XSS) mechanics, safe DOM manipulation, innerHTML vs textContent, and the validation vs sanitization pipeline.

JavaScriptShallow vs. Deep Copy (Spread Pitfalls & JSON Limits)

Understanding object references, shallow copy pitfalls with spread, JSON limitations, and structuredClone.

JavaScriptWeb Storage: localStorage, sessionStorage & Cookies

Client-side storage mechanisms in JavaScript: comparing localStorage, sessionStorage, and Cookies for interview prep.

async / await & Modern Asynchronous Flow

While Promises solved callback hell, chained .then() and .catch() callbacks can still feel unnatural to read, mentally reverse control flow, and make step-by-step debugging cumbersome.

ECMAScript 2017 introduced async / await as syntax sugar built entirely on top of Promises. It allows developers to structure asynchronous logic using linear, top-to-bottom syntax that reads like synchronous code while preserving non-blocking performance:

$$\text{Promises = The Engine} \qquad \longleftrightarrow \qquad \text{async / await = The Steering Wheel}$$

Diagram illustrating JavaScript async function wrapping, await execution suspension, and sequential vs parallel concurrency flows
The async/await mental model: automatic Promise wrapping, non-blocking function suspension, and parallel vs. sequential execution.

1. The async Keyword & Automatic Promise Wrapping

Adding async before a function declaration, expression, or arrow function transforms it into a Promise factory with two fundamental rules:

  1. Always Returns a Promise: If you return a primitive value or an object, JavaScript automatically wraps it with Promise.resolve(value).
  2. Passes Existing Promises Through: If you return a Promise explicitly, JavaScript does not wrap it twice; it returns the Promise as-is.
  3. Thrown Errors Become Rejections: If an exception is thrown inside an async function, it is converted into Promise.reject(error).
async-wrapping.js
// 1. Implicit Promise wrapping of primitive returns
async function getScore() {
  return 100; // Automatically equivalent to: return Promise.resolve(100);
}

// Consuming via .then() confirms it returns a Promise
getScore().then(val => console.log("Score:", val)); // "Score: 100"

// 2. Thrown errors become rejected Promises automatically
async function failTask() {
  throw new Error("Database timeout"); // Equivalent to: return Promise.reject(new Error(...))
}

failTask().catch(err => console.error("Rejected:", err.message)); // "Rejected: Database timeout"
Every async function returns a Promise, and thrown errors automatically reject that returned Promise.

2. The await Keyword & Non-Blocking Suspension

The await keyword can only be used inside async functions (or at top-level modules). It pauses execution until the awaited Promise settles:

  • If the Promise fulfills, await unwraps and extracts the resolved value directly into your variable.
  • If the Promise rejects, await throws the rejection reason as an exception.

Why await Does NOT Freeze the Browser

Beginners often fear that pausing code blocks the entire program. However, await only yields control back to the JavaScript event loop. While the async function waits, the engine continues processing UI user clicks, rendering animations, and handling other I/O operations.

await-suspension.js
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

async function loadDashboard() {
  console.log("2. Starting dashboard fetch...");
  await delay(100); // Suspends loadDashboard, returns control to the event loop
  console.log("4. Dashboard data ready!");
}

console.log("1. Script starts");
loadDashboard();
console.log("3. Main thread continues immediately");

// Console Output:
// 1. Script starts
// 2. Starting dashboard fetch...
// 3. Main thread continues immediately
// 4. Dashboard data ready!
await pauses only the local function; the main thread continues running subsequent synchronous tasks.

3. Sequential vs. Parallel Execution (Waterfall Prevention)

One of the most dangerous performance antipatterns in modern JavaScript is the accidental async waterfall:

  • Sequential Execution: Awaiting calls one after another when they don't depend on each other. If Call A takes 300ms and Call B takes 300ms, total latency is 600ms.
  • Parallel Execution: Starting both asynchronous operations concurrently before awaiting them together using Promise.all(). Total latency is only 300ms (the longest single request).
concurrency-patterns.js
async function fetchUser() { /* takes 200ms */ return { id: 1, name: "Sara" }; }
async function fetchPosts() { /* takes 200ms */ return ["Post 1", "Post 2"]; }

// ❌ SLOW: Accidental Sequential Waterfall (Total: 400ms)
async function loadSlow() {
  const user = await fetchUser();   // waits 200ms
  const posts = await fetchPosts(); // starts AFTER user finishes (waits another 200ms)
  return { user, posts };
}

// ✅ FAST: Parallel Execution with Promise.all (Total: 200ms)
async function loadFast() {
  // Both network requests fire simultaneously
  const [user, posts] = await Promise.all([
    fetchUser(),
    fetchPosts()
  ]);
  return { user, posts };
}
Use sequential await only when task B requires data from task A. Independent tasks must always run concurrently.

4. Error Handling with try / catch & Propagation

Because await converts a Promise rejection into a thrown exception, asynchronous error handling maps directly onto synchronous try / catch constructs.

Error Propagation (Async Call Stacks)

If an error occurs inside a deeply nested async function and is not caught locally, it bubbles upward through the calling async functions until it hits an enclosing try / catch boundary. If it reaches the top level without being caught, it produces an UnhandledPromiseRejection.

async-error-propagation.js
async function queryDatabase() {
  // Simulating a failed query
  throw new Error("Connection lost: Port 5432 unreachable");
}

async function getBillingProfile() {
  // Error in queryDatabase() propagates through this unhandled step
  return await queryDatabase();
}

async function handleCheckout() {
  try {
    console.log("Attempting checkout...");
    const profile = await getBillingProfile();
    console.log("Profile loaded:", profile);
  } catch (error) {
    // Catches the rejection that bubbled all the way from queryDatabase
    console.error("Checkout failed safely:", error.message);
  } finally {
    console.log("Checkout cleanup complete.");
  }
}
Errors propagate upward through awaited async callers until intercepted by a try/catch boundary.
Asynchronous Flow Execution Strategies

Pattern

Syntax Structure

Execution Timing

Failure Behavior

Recommended Use Case

Sequential await

const a = await f1(); const b = await f2(a);

One by one (sum of all latencies)

First rejection halts remaining steps immediately

Dependent operations (step 2 needs step 1's output)

Parallel Promise.all

const [a, b] = await Promise.all([f1(), f2()]);

Concurrent (longest single request latency)

Rejects immediately if ANY promise fails (fail-fast)

Independent operations where all results are strictly mandatory

Resilient Promise.allSettled

const results = await Promise.allSettled([f1(), f2()]);

Concurrent (waits for all)

Never rejects; provides status array

Independent operations where partial batch success is permitted

Fire-and-Forget

trackEvent(data); // No await

Background async; caller does not wait

Errors must be handled internally via .catch()

Non-critical analytics, background telemetry, cache warming

Think it throughActivity 1: What is the exact execution order and console output of this code snippet?
async function test() {
  console.log("A");
  const res = await Promise.resolve("B");
  console.log(res);
  console.log("C");
}

console.log("1");
test();
console.log("2");

Output: 1 A 2 B C

Explanation:

  1. console.log("1") executes synchronously $\rightarrow$ prints 1.
  2. test() is called synchronously $\rightarrow$ executes up to the await, printing A.
  3. The await Promise.resolve("B") pauses test() and queues its resumption as a microtask.
  4. Synchronous execution resumes in the caller $\rightarrow$ prints 2.
  5. The call stack clears; the microtask runs $\rightarrow$ prints B, then C.
Think it throughActivity 2: Refactor this buggy user-fetching code to run in parallel and safely handle errors:
// ❌ Buggy & Slow code:
async function fetchTeamProfiles(userIds) {
  const profiles = [];
  userIds.forEach(async (id) => {
    const profile = await fetchProfile(id); // forEach won't wait!
    profiles.push(profile);
  });
  return profiles; // Returns [] immediately before fetches finish!
}

✅ Refactored Solution:

async function fetchTeamProfiles(userIds) {
  try {
    // Map IDs to concurrent promises, then await all together
    const profilePromises = userIds.map(id => fetchProfile(id));
    const profiles = await Promise.all(profilePromises);
    return profiles;
  } catch (error) {
    console.error("Failed to load team profiles:", error);
    throw error;
  }
}

Why this works:

  • map() returns an array of in-flight Promises running simultaneously.
  • Promise.all() waits for all requests to finish before resolving.
  • try / catch safely captures any rejection during the batch fetch.