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.

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

Copying objects in JavaScript looks simple, but many invisible production bugs originate from copying the wrong way. Primitive values (numbers, strings, booleans) copy by value. Objects and arrays, however, are copied by reference.

Understanding the distinction between shallow copying and deep copying is critical for predictable state management, UI rendering, and preventing unintended mutations.

Diagram comparing Reference Assignment, Shallow Copy with shared nested references, and Deep Copy with structuredClone
Shallow copying creates a new top-level container but retains shared memory pointers to nested objects.

1. Shallow Copy & The Spread Pitfall

A shallow copy duplicates top-level properties. If a property is a primitive, it gets a new value. But if a property is an object or array, only its memory address is copied.

Common shallow copy methods:

  • Object Spread: const copy = { ...user };
  • Object Assign: const copy = Object.assign({}, user);
  • Array Slice / Spread: const copyArr = [...arr];
shallow-pitfall.js
const user = {
  name: "Ali",
  settings: {
    theme: "dark"
  }
};

// Shallow copy with spread operator
const copy = { ...user };

// Mutating a nested property on the copy
copy.settings.theme = "light";

console.log(user.settings.theme); // ❌ Output: "light" (Accidentally mutated!)
console.log(user.settings === copy.settings); // true (Same reference in memory!)
user.settings and copy.settings point to the exact same nested object in the heap.

2. The JSON Serialization Trick & Its Critical Limits

A widely known shortcut for deep copying is JSON.parse(JSON.stringify(obj)).

While convenient for simple data objects, it fails in production when data types go beyond basic JSON:

json-limitations.js
const complexData = {
  createdAt: new Date(),
  greet: () => "Hello",
  score: undefined,
  tags: new Set(["js", "ts"]),
  price: NaN
};

// The JSON stringify/parse serialization trick
const jsonCopy = JSON.parse(JSON.stringify(complexData));

console.log(jsonCopy.createdAt); // "2026-10-08T..." (Date converted to string!)
console.log(jsonCopy.greet);     // undefined (Functions dropped!)
console.log(jsonCopy.score);     // undefined (undefined keys dropped!)
console.log(jsonCopy.tags);      // {} (Set converted to empty object!)
console.log(jsonCopy.price);     // null (NaN converted to null!)
JSON serialization drops functions/undefined, loses Set/Map instances, and turns Date objects into strings.

3. Proper Deep Copy: structuredClone()

Modern JavaScript now includes structuredClone(), a native global function built into all modern browsers and Node.js (v17+).

Why structuredClone() is the Modern Standard:

  • Clones all nested levels recursively.
  • Correctly preserves Date, Set, Map, RegExp, and ArrayBuffer instances.
  • Safely handles circular references without throwing errors.
structured-clone.js
const user = {
  name: "Ali",
  joined: new Date(),
  tags: new Set(["admin", "editor"]),
  settings: {
    theme: "dark"
  }
};

// Modern, native deep clone
const deep = structuredClone(user);

deep.settings.theme = "light";
deep.tags.add("author");

console.log(user.settings.theme); // "dark" (Safe! Not mutated)
console.log(user.tags.size);       // 2 (Independent Set)
console.log(deep.joined instanceof Date); // true (Preserves Date instance)
structuredClone() creates a completely isolated duplicate without shared heap pointers.
Comparison: Copying Strategies in JavaScript

Strategy

Syntax

Copies Nested Levels?

Preserves Dates & Sets?

Circular References?

Performance

Reference Assignment

b = a

No (Same object pointer)

N/A

Yes

Instant (Zero allocation)

Shallow Copy

{ ...obj } / Object.assign()

No (Level 1 only)

Preserves references

Yes

Extremely fast

JSON Serialization

JSON.parse(JSON.stringify())

Yes (All levels)

No (Lossy data conversion)

No (Crashes with TypeError)

Slow (String parsing)

structuredClone()

structuredClone(obj)

Yes (All levels)

Yes (Native preservation)

Yes (Handles cycles)

Fast native engine clone

Think it throughInterview Question: How does React / Redux perform immutable state updates safely using shallow copying?

Instead of an expensive full deep clone on every user interaction, React and Redux state reducers use nested shallow spreads on only the branches that change:

// Update user.settings.theme immutably:
const nextState = {
  ...state,
  user: {
    ...state.user,
    settings: {
      ...state.user.settings,
      theme: 'light'
    }
  }
};

Why this matters for performance: Unchanged branches retain identical memory references (prev.posts === next.posts), allowing React components wrapped in React.memo to skip unnecessary re-renders via fast reference equality checks.