Topic 08 / 10

Modern ES6+ Features: Modules, Set, Map, Optional Chaining & structuredClone

1. Simple Definition

Modern JavaScript (ES2015 se lekar ES2024+) ne language me aise powerful features introduce kiye hain jo code ko saaf, modular aur crash-proof banate hain. Inme ES Modules (code splitting), Set & Map (high performance unique collections), Optional Chaining (?.) (undefined error killer), aur structuredClone() (perfect deep copy) shamil hain.

2. Real-Life Analogy

🧩 Lego Blocks & Safety Sensors

ES Modules: Har Lego block alag dabba me hai (math.js, ui.js). Jab zaroorat ho sirf wahi block import karo. Poora dabba ek hi file me nahi thopna padta.
Optional Chaining (?.): Car ka proximity sensor: Agar aage deewar hai toh car crash nahi hoti, sensor ruk jata hai (bina Uncaught TypeError throw kiye)!

3. Why Do We Need It?

Badi real-world applications me agar 10,000 lines of code ek hi single file me ho, toh organize karna namumkin ho jata hai. ES Modules code ko maintainable banate hain. Aur real backend APIs se aane wale messy nested objects ko bina application crash kiye safely read karne ke liye modern operators zaroori hain.

4. Syntax Overview

// 1. ES Modules (Named & Default Export/Import)
// file: utils.js
export const TAX_RATE = 0.18;
export function calculateTax(amount) {
  return amount * TAX_RATE;
}
export default function logger(msg) { console.log("[LOG]:", msg); }

// file: main.js
import logger, { TAX_RATE, calculateTax } from './utils.js';

// 2. Set (Only Unique Values, Zero Duplicates!)
const tags = new Set(["html", "css", "html", "javascript"]);
console.log([...tags]); // ["html", "css", "javascript"] (Duplicate 'html' auto removed)

// 3. Map (Fast Key-Value Pair, Keys can be Any Data Type)
const userRoles = new Map();
const user1 = { id: 1 };
userRoles.set(user1, "Administrator"); // Object itself is a key!
console.log(userRoles.get(user1)); // "Administrator"

// 4. Optional Chaining (?.) & Nullish Coalescing (??)
const apiResponse = { user: { name: "Aman" } };
// Safe read (Crash nahi karega agar address undefined ho)
const city = apiResponse?.user?.address?.city ?? "Default City (Delhi)";
console.log(city); // "Default City (Delhi)"

// 5. Native Deep Cloning with structuredClone()
const original = { id: 1, info: { theme: "dark" }, date: new Date() };
const trueCopy = structuredClone(original);
trueCopy.info.theme = "light";
console.log(original.info.theme); // "dark" (Original bilkul safe raha!)

5. Basic Example: Unique Category Filter from E-Commerce List

const products = [
  { id: 1, title: "Laptop", category: "Electronics" },
  { id: 2, title: "T-Shirt", category: "Fashion" },
  { id: 3, title: "Mouse", category: "Electronics" },
  { id: 4, title: "Jeans", category: "Fashion" },
  { id: 5, title: "Coffee Mug", category: "Home" }
];

// Extract Unique Categories in 1 Line using Set
const uniqueCategories = ["All", ...new Set(products.map(p => p.category))];
console.log(uniqueCategories);
// Output: ["All", "Electronics", "Fashion", "Home"]

6. Output & Interactive Safe-Accessor Simulator

Click above buttons to test difference...

7. Code Explanation: Deep Clone vs Shallow Clone

Method Type Nested Objects Dates & Special Objects
{ ...original } (Spread) Shallow Copy ❌ Reference copied (Nested changes affect original) Reference copied
JSON.parse(JSON.stringify()) Fake Deep Copy ✅ Cloned ❌ Dates become strings, fails on functions/circular
structuredClone(original) True Deep Copy ✅ 100% Independent ✅ Preserves Dates, Sets, Maps, RegEx natively

8. Real-World Example: Safe API Config Fallback

function renderPlayerScore(userSettings) {
  // CRITICAL: ?? vs || difference!
  // Agar score 0 hai, toh 0 ek VALID number hai!
  // || operator 0 ko falsy man kar 100 bana dega (BUG)
  // ?? operator 0 ko preserve karega (CORRECT)
  const score = userSettings?.game?.score ?? 100;
  const isMuted = userSettings?.audio?.muted ?? false;
  
  console.log(`Current Score: ${score}, Audio Muted: ${isMuted}`);
}

renderPlayerScore({ game: { score: 0 } }); // Output: Current Score: 0 (Properly preserved!)

9. Common Mistakes

⚠️ Falsy Trap: '||' vs '??'

Kabhi bhi numbers (jaise count: 0) ya booleans (jaise notifications: false) ke liye || use na karein! Kyunki 0 || 10 output 10 deta hai. Nullish Coalescing (??) sirf aur sirf null ya undefined aane par default fallback lagata hai.

10. Best Practices

  • HTML me module use karte waqt <script type="module" src="app.js"></script> lagana zaroori hai (ye automatic defer behave karta hai).
  • Array me se duplicates hatane ke liye [...new Set(array)] sabse fast aur clean pattern hai.
  • Deep objects ko clone karte waqt bina kisi external library (jaise Lodash cloneDeep) ke native structuredClone() use karein.

11. Try It Yourself

Playground me const m = new Map(); m.set("count", 1); m.set("count", m.get("count") + 1); console.log(m.get("count")); likh kar word counter test karein.

12. Challenge

Ek Word Frequency Counter banayein: Diye gaye sentence ke sabhi words ko tod kar Map me count karein ki kaunsa word kitni baar aaya hai.

13. Interview Questions

💼 Q1: Set aur Array me search performance ka kya farq hai?

Answer: Array me arr.includes(item) karne par time complexity O(N) hoti hai (poora array iterate hota hai). Set me set.has(item) karne par time complexity O(1) (Instant Hash Lookup) hoti hai. Badi collections me Set hazaron guna fast hota hai.

💼 Q2: ES Modules (ESM) aur CommonJS (CJS) me kya farq hai?

Answer: ESM (import/export) static hota hai, browser aur modern Node.js dono me natively chalta hai aur build tools me Tree Shaking (unused code removal) support karta hai. CJS (require/module.exports) dynamic hota hai aur legacy Node.js me use hota tha.

14. Quick Revision

  • import / export creates modular, clean codebases.
  • Set stores unique values (Instant [...new Set(arr)] dedupe).
  • Map allows any key type and preserves insertion order.
  • ?. prevents TypeError crashes; ?? handles null/undefined fallbacks safely.
  • structuredClone() is browser's built-in true deep copier.

15. FAQ

Q1. Kya HTML me module script CORS restriction follow karti hai?

Haan! <script type="module"> ko local file:/// ke bajaye local web server (jaise Live Server ya Vite) se chalana padta hai.

Q2. WeakMap aur WeakSet kya hote hain?

Ye aisi collections hain jahan keys sirf objects hoti hain aur unke garbage collection references weak hote hain (memory leak rokne ke liye).

Q3. structuredClone functions copy kar sakta hai?

Nahi! Functions aur DOM nodes structuredCloneable nahi hote (Data structures aur objects copy hote hain).

Q4. Kya Set me objects unique hote hain?

Objects reference ke hisab se compare hote hain. Do alag {} objects Set me duplicate nahi maane jayenge kyunki unka memory address alag hota hai.

Q5. Dynamic import kya hota hai?

import('./module.js').then(...) jisse aap kisi code module ko sirf tab download karte hain jab user us button par click kare (Lazy Loading).

Topic 08 / 10

Modern ES6+ Features: Modules, Set, Map, Optional Chaining & structuredClone

1. Simple Definition

Modern ES6+ Features represent the latest evolutions of ECMAScript that elevate JavaScript into a mature, modular, enterprise-grade language. These include ES Modules (import / export), high-performance data structures (Set and Map), Optional Chaining (?.), and native deep cloning via structuredClone().

2. Real-Life Analogy

🧰 Modular Tool Kit vs Single Cluttered Toolbox

Instead of carrying a 50kg bag containing every tool ever invented (a massive 10,000-line monolithic script), you organize specialized modular cases: electrical tools in one case, plumbing in another (ES Modules). When wiring a switch, you only unpack the specific wire-stripper you need (Named Imports)!

3. ES Modules: Export and Import

// 1. In utils.js (Exporting functions)
export const formatCurrency = (amount) => `$${amount.toFixed(2)}`;
export const calculateTax = (amount, rate = 0.18) => amount * rate;

// Default export
export default function logger(msg) {
  console.log(`[APP LOG]: ${msg}`);
}

// 2. In app.js (Importing modules)
import logger, { formatCurrency, calculateTax } from './utils.js';

logger("Computing order totals...");
console.log(formatCurrency(199.5)); // "$199.50"

4. Set & Map Data Structures

// 1. Set: Collection of GUARANTEED UNIQUE values (instant deduplication!)
const tags = ["js", "css", "html", "js", "css"];
const uniqueTags = [...new Set(tags)]; // ["js", "css", "html"]

// 2. Map: Key-value dictionary where KEYS can be ANY type (including objects!)
const userRoles = new Map();
const userObj = { id: 101 };
userRoles.set(userObj, "Administrator");
console.log(userRoles.get(userObj)); // "Administrator"

5. Common Mistakes

⚠️ Common Pitfall: Omitting type="module" in HTML

If you load a script containing import / export without adding <script type="module" src="app.js">, the browser will throw a fatal SyntaxError: Cannot use import statement outside a module!

6. Best Practices

  • Always break large files into single-responsibility ES modules.
  • Use Set whenever you need to filter duplicate values or check membership in O(1) time.
  • Use Map when keys are dynamically determined or are non-string objects.

7. Practice Exercise

🎯 Exercise: Array Deduplicator

Create an array containing 10 numbers with repeated entries (e.g. [1, 2, 2, 3, 4, 4, 5]) and produce a unique array in one line of code using Set and the spread operator.

8. Interview Questions

💼 Q: How does Map differ from a plain JavaScript Object?

Answer: A plain Object only allows strings and Symbols as keys; a Map accepts any data type as key (including objects, arrays, and functions). Maps preserve insertion order, provide a direct .size property, and offer optimized performance for frequent insertions and deletions.

9. Summary / Cheat Card

  • ES Modules: import and export clean modular dependencies.
  • Set stores unique values; instant array deduplication.
  • Map maps arbitrary keys to values.
  • structuredClone() creates deep, safe object copies.

10. FAQ

Q1. Do ES Modules run in strict mode?

Yes! Scripts loaded with type="module" automatically execute in JavaScript's "use strict" mode by default.