[{"data":1,"prerenderedAt":548},["ShallowReactive",2],{"all-questions-javascript":3},{"beginner":4,"intermediate":208,"advanced":371},[5,15,24,33,41,49,56,67,75,84,91,100,107,116,124,131,138,144,151,160,170,177,186,193,200],{"id":6,"category":7,"question":8,"answer":9,"level":10,"tags":11},1,"Basics","What is JavaScript? Explain its role in web development and key characteristics.","**Concept Explanation:**\nJavaScript is a high-level, dynamic, interpreted (or JIT-compiled) programming language primarily used for adding interactivity and dynamic behavior to web pages. It is a core technology of the World Wide Web alongside HTML and CSS, and it runs on the client-side (browser) as well as server-side (Node.js).\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Variables\nlet message = 'Hello, World!';\n\n\u002F\u002F Function\nfunction greet() {\n  console.log(message);\n}\n\ngreet(); \u002F\u002F Output: Hello, World!\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F DOM manipulation\ndocument.getElementById('myButton').addEventListener('click', () => {\n  alert('Button clicked!');\n});\n```\n\n**Execution Flow:**\n1. Browser loads HTML with `\u003Cscript>` tags or external `.js` files.\n2. JavaScript engine parses code, identifies declarations, and enters execution context.\n3. Code runs synchronously unless asynchronous operations (timers, events) are scheduled via event loop.\n\n**Practical Usage:**\n- Form validation on client-side\n- Dynamic content updates without page reload (AJAX\u002Ffetch)\n- Interactive maps, animations, games\n\n**Interview Insight:**\nStart with definition, highlight single-threaded but asynchronous nature via event loop. Mention both browser and Node.js environments.\n\n**Common Mistakes:**\n- Forgetting case-sensitivity\n- Misunderstanding asynchronous flow\n- Overlooking browser compatibility for modern features\n\n**Real-world Example:**\nSubmitting a form and seeing a loading spinner without page refresh – JavaScript makes asynchronous request (fetch) and updates DOM.\n\n**Advanced Notes:**\nJavaScript engines (V8, SpiderMonkey) use Just-In-Time compilation. The language follows ECMAScript specification (ES2025+ includes features like top-level await, Temporal API).","beginner",[12,13,14],"basics","javascript","web-development",{"id":16,"category":17,"question":18,"answer":19,"level":10,"tags":20},2,"Variables & Scope","Explain the differences between var, let, and const in JavaScript. How do they affect variable scope and reassignment?","**Concept Explanation:**\n`var`, `let`, and `const` are used for variable declaration in JavaScript. `var` is function-scoped and hoisted with `undefined`, `let` and `const` are block-scoped and hoisted without initialization (Temporal Dead Zone). `const` cannot be reassigned, but its properties can be mutated.\n\n**Syntax Explanation:**\n```javascript\nvar a = 10;       \u002F\u002F function-scoped, can be redeclared\nlet b = 20;       \u002F\u002F block-scoped, cannot be redeclared in same scope\nconst c = 30;     \u002F\u002F block-scoped, cannot be reassigned\n\nif (true) {\n  var x = 1;      \u002F\u002F accessible outside block\n  let y = 2;      \u002F\u002F only inside block\n  const z = 3;    \u002F\u002F only inside block\n}\nconsole.log(x);   \u002F\u002F 1\nconsole.log(y);   \u002F\u002F ReferenceError\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F const with objects\nconst user = { name: 'John' };\nuser.name = 'Jane';   \u002F\u002F Allowed (property mutation)\n\u002F\u002F user = {};         \u002F\u002F TypeError: Assignment to constant variable\n\n\u002F\u002F Temporal Dead Zone\nconsole.log(myVar);   \u002F\u002F undefined (var)\nvar myVar = 5;\nconsole.log(myLet);   \u002F\u002F ReferenceError (TDZ)\nlet myLet = 10;\n```\n\n**Execution Flow:**\n- `var`: During creation phase, variable is hoisted and initialized with `undefined`.\n- `let`\u002F`const`: Hoisted but not initialized; accessing before declaration throws ReferenceError.\n\n**Practical Usage:**\n- Use `const` by default for values that shouldn't be reassigned.\n- Use `let` when reassignment is needed (loop counters, accumulators).\n- Avoid `var` in modern code due to unexpected scoping and redeclaration issues.\n\n**Interview Insight:**\nExplain TDZ clearly – it prevents accessing variables before declaration, catching errors early.\n\n**Common Mistakes:**\n- Using `const` for primitive values that need reassignment.\n- Assuming `const` makes objects immutable.\n- Relying on `var` hoisting leading to undefined behavior.\n\n**Real-world Example:**\nDeclaring API base URL with `const` (never changes), loop index with `let`, legacy codebases may still use `var`.\n\n**Advanced Notes:**\n`let` and `const` were introduced in ES6. The Temporal Dead Zone exists from block entry until declaration; even `typeof` throws ReferenceError in TDZ.",[21,22,23],"variables","scope","es6",{"id":25,"category":7,"question":26,"answer":27,"level":10,"tags":28},3,"What are the primitive data types in JavaScript? Explain the difference between null and undefined.","**Concept Explanation:**\nJavaScript has seven primitive data types: `string`, `number`, `bigint`, `boolean`, `undefined`, `symbol`, and `null`. Primitives are immutable and stored directly on the stack. `undefined` means a variable has been declared but not assigned a value; `null` is an intentional absence of any object value.\n\n**Syntax Explanation:**\n```javascript\nlet name = 'Alice';        \u002F\u002F string\nlet age = 30;              \u002F\u002F number\nlet isActive = true;       \u002F\u002F boolean\nlet big = 9007199254740991n; \u002F\u002F bigint\nlet id = Symbol('id');     \u002F\u002F symbol\nlet notDefined;            \u002F\u002F undefined\nlet emptyValue = null;     \u002F\u002F null\n\nconsole.log(typeof null);          \u002F\u002F 'object' (historical bug)\nconsole.log(typeof undefined);     \u002F\u002F 'undefined'\nconsole.log(null == undefined);    \u002F\u002F true (loose equality)\nconsole.log(null === undefined);   \u002F\u002F false (strict equality)\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Checking for undefined\nlet x;\nif (x === undefined) { \u002F* true *\u002F }\n\n\u002F\u002F Checking for null\nlet y = null;\nif (y === null) { \u002F* true *\u002F }\n\n\u002F\u002F Default values with nullish coalescing\nlet value = null ?? 'default';  \u002F\u002F 'default'\nlet value2 = undefined ?? 'default'; \u002F\u002F 'default'\n```\n\n**Execution Flow:**\n- `undefined` is automatically assigned by JavaScript engine during variable hoisting (for `var`) or when a property doesn't exist.\n- `null` must be explicitly assigned by the developer.\n\n**Practical Usage:**\n- Use `undefined` to indicate missing\u002Finitalized value.\n- Use `null` to explicitly reset or indicate 'no value' for objects.\n- Use optional chaining (`?.`) to safely access nested properties that might be `null`\u002F`undefined`.\n\n**Interview Insight:**\nMention `typeof null === 'object'` is a known bug from early JavaScript. `undefined` is a primitive type, `null` is also primitive but appears as object due to spec.\n\n**Common Mistakes:**\n- Confusing loose equality: `null == 0` is false, `null == false` is false.\n- Forgetting to check for both `null` and `undefined` when needed.\n\n**Real-world Example:**\nAPI response might return `null` for missing fields, while accessing a non-existent object property yields `undefined`.\n\n**Advanced Notes:**\n`undefined` is not a reserved word but a global property; can be shadowed (not recommended). `Null` is a literal. Use `void 0` to safely get `undefined`.",[29,30,31,32],"data-types","primitives","null","undefined",{"id":34,"category":35,"question":36,"answer":37,"level":10,"tags":38},4,"Functions","What are the different ways to define functions in JavaScript? Compare function declarations, function expressions, and arrow functions.","**Concept Explanation:**\nFunctions are reusable blocks of code. Function declarations are hoisted, function expressions are not hoisted, arrow functions provide lexical `this` binding and shorter syntax.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Function Declaration (hoisted)\nfunction add(a, b) {\n  return a + b;\n}\n\n\u002F\u002F Function Expression (not hoisted)\nconst multiply = function(a, b) {\n  return a * b;\n};\n\n\u002F\u002F Arrow Function (ES6)\nconst subtract = (a, b) => a - b;\n\n\u002F\u002F Arrow with block body\nconst divide = (a, b) => {\n  if (b === 0) throw new Error('Division by zero');\n  return a \u002F b;\n};\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Hoisting difference\nsayHello(); \u002F\u002F Works (function declaration)\nfunction sayHello() { console.log('Hello'); }\n\nsayHi();    \u002F\u002F TypeError: sayHi is not a function (expression)\nconst sayHi = () => console.log('Hi');\n\n\u002F\u002F 'this' binding difference\nconst obj = {\n  name: 'React',\n  regularFunc: function() { console.log(this.name); },\n  arrowFunc: () => console.log(this.name)\n};\nobj.regularFunc(); \u002F\u002F 'React'\nobj.arrowFunc();   \u002F\u002F undefined (lexical this from outer scope)\n```\n\n**Execution Flow:**\n- Function declarations are hoisted completely, can be called before definition.\n- Function expressions and arrow functions follow normal variable hoisting (TDZ for `let`\u002F`const`).\n\n**Practical Usage:**\n- Use arrow functions for callbacks to preserve `this`.\n- Use function declarations for top-level utilities due to hoisting.\n- Use function expressions for conditional function creation.\n\n**Interview Insight:**\nArrow functions lack their own `this`, `arguments`, `super`, and cannot be used as constructors (no `new`).\n\n**Common Mistakes:**\n- Using arrow functions as object methods (loses proper `this`).\n- Expecting arrow functions to have `arguments` object.\n\n**Real-world Example:**\nReact class components often use arrow functions for event handlers to bind `this` automatically.\n\n**Advanced Notes:**\nAsync arrow functions: `const fetchData = async () => { ... }`. Generators cannot be arrow functions. Arrow functions have implicit return when body is a single expression without braces.",[39,23,40],"functions","arrow-functions",{"id":42,"category":7,"question":43,"answer":44,"level":10,"tags":45},5,"Explain truthy and falsy values in JavaScript. How does type coercion work with equality operators (== vs ===)?","**Concept Explanation:**\nFalsy values are treated as `false` in boolean contexts: `false`, `0`, `-0`, `0n`, `''`, `null`, `undefined`, `NaN`. Everything else is truthy. Loose equality (`==`) performs type coercion, while strict equality (`===`) checks both value and type without coercion.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Falsy values\nif (false) {}\nif (0) {}\nif ('') {}\nif (null) {}\nif (undefined) {}\nif (NaN) {}\n\n\u002F\u002F Truthy values\nif (true) {}\nif (1) {}\nif ('hello') {}\nif ({}) {}\nif ([]) {}\n\n\u002F\u002F Equality comparison\n5 == '5';   \u002F\u002F true (coercion)\n5 === '5';  \u002F\u002F false (different types)\nnull == undefined;  \u002F\u002F true\nnull === undefined; \u002F\u002F false\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Type coercion rules\n0 == false;      \u002F\u002F true (false -> 0)\n'' == false;     \u002F\u002F true\n[] == false;     \u002F\u002F true ([] -> '' -> 0)\n[] == ![];       \u002F\u002F true (coercion quirk)\n\n\u002F\u002F Avoid coercion pitfalls\nif (value == null) { }  \u002F\u002F Checks both null and undefined (acceptable use)\nif (value === null) { } \u002F\u002F Strict check\n```\n\n**Execution Flow:**\nWhen `==` is used, JavaScript converts operands to common type using the Abstract Equality Comparison algorithm: string to number, boolean to number, object to primitive via `ToPrimitive`.\n\n**Practical Usage:**\n- Always prefer `===` unless intentionally using coercion.\n- Use double negation `!!value` to convert any value to boolean.\n- Default parameters and short-circuiting rely on truthiness: `const name = input || 'Guest'`.\n\n**Interview Insight:**\n`==` is not transitive in some edge cases (e.g., `[] == ![]`). Modern codebases enforce `===` via linters. Only `== null` is a common pattern to check for `null` or `undefined`.\n\n**Common Mistakes:**\n- Using `==` with `0` and `false` leading to unexpected truth.\n- Assuming `NaN === NaN` (false, use `isNaN()` or `Number.isNaN()`).\n\n**Real-world Example:**\nForm validation: `if (inputValue)` triggers for non-empty strings, numbers except 0, etc. But `0` might be a valid input – causing bug.\n\n**Advanced Notes:**\n`Object.is()` is even stricter than `===` (handles `-0` and `NaN` differently). `+0 === -0` is true, `Object.is(+0, -0)` false; `NaN === NaN` false, `Object.is(NaN, NaN)` true.",[46,47,48],"coercion","equality","truthy-falsy",{"id":50,"category":17,"question":51,"answer":52,"level":10,"tags":53},6,"What is hoisting in JavaScript? How does it work with var, let\u002Fconst, and function declarations?","**Concept Explanation:**\nHoisting is JavaScript's behavior where variable and function declarations are moved to the top of their containing scope during compilation. `var` declarations are hoisted and initialized with `undefined`; `let`\u002F`const` are hoisted but not initialized (Temporal Dead Zone); function declarations are hoisted entirely (definition available before execution).\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F var hoisting\nconsole.log(a); \u002F\u002F undefined\nvar a = 5;\n\n\u002F\u002F let\u002Fconst hoisting (TDZ)\nconsole.log(b); \u002F\u002F ReferenceError\nlet b = 10;\n\n\u002F\u002F function hoisting\nsayHello(); \u002F\u002F 'Hello'\nfunction sayHello() {\n  console.log('Hello');\n}\n\n\u002F\u002F Function expression hoisting (not hoisted)\nsayHi(); \u002F\u002F TypeError\nconst sayHi = () => console.log('Hi');\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Temporal Dead Zone example\n{\n  \u002F\u002F TDZ starts\n  console.log(x); \u002F\u002F ReferenceError\n  let x = 1;\n  \u002F\u002F TDZ ends\n}\n\n\u002F\u002F Hoisting with block scope\nif (true) {\n  var foo = 'bar'; \u002F\u002F hoisted to function\u002Fglobal scope\n  let baz = 'qux'; \u002F\u002F hoisted but TDZ within block\n}\nconsole.log(foo); \u002F\u002F 'bar'\nconsole.log(baz); \u002F\u002F ReferenceError\n```\n\n**Execution Flow:**\n1. Parser reads code, identifies declarations.\n2. For `var`: storage is allocated, initialized with `undefined`.\n3. For `let`\u002F`const`: storage allocated but not initialized (cannot access).\n4. Function declarations: function object is created and bound to identifier.\n5. Execution phase: assignments happen in-place.\n\n**Practical Usage:**\n- Rely on function hoisting for organizing code (define functions at bottom, call at top).\n- Avoid relying on `var` hoisting – always declare variables at top of scope.\n- Use `let`\u002F`const` to catch TDZ errors early.\n\n**Interview Insight:**\nHoisting is a mental model – actual implementation involves lexical environments. Function hoisting allows mutually recursive functions without order constraints.\n\n**Common Mistakes:**\n- Assuming `let`\u002F`const` are not hoisted (they are, but TDZ prevents access).\n- Using variable before declaration with `let` expecting `undefined` like `var`.\n\n**Real-world Example:**\nIn legacy codebases, you might see `var` declarations after usage – still works due to hoisting but confusing. Modern ESLint rules `no-use-before-define` prevent this.\n\n**Advanced Notes:**\nClass declarations are hoisted but also TDZ: `const obj = new MyClass(); class MyClass {}` – ReferenceError. `import` statements are hoisted, modules are evaluated before the module code executes.",[54,22,55],"hoisting","tdz",{"id":57,"category":58,"question":59,"answer":60,"level":10,"tags":61},7,"Arrays","What are common array methods in JavaScript? Explain map, filter, and reduce with examples.","**Concept Explanation:**\nArray methods provide functional programming capabilities. `map()` creates new array by transforming each element; `filter()` creates new array with elements passing a test; `reduce()` accumulates array into single value. All three do not mutate original array.\n\n**Syntax Explanation:**\n```javascript\nconst numbers = [1, 2, 3, 4, 5];\n\n\u002F\u002F map: transform each element\nconst doubled = numbers.map(n => n * 2); \u002F\u002F [2,4,6,8,10]\n\n\u002F\u002F filter: keep elements meeting condition\nconst evens = numbers.filter(n => n % 2 === 0); \u002F\u002F [2,4]\n\n\u002F\u002F reduce: accumulate\nconst sum = numbers.reduce((acc, curr) => acc + curr, 0); \u002F\u002F 15\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Real-world: extract names from users\nconst users = [{name: 'Alice'}, {name: 'Bob'}];\nconst names = users.map(u => u.name); \u002F\u002F ['Alice','Bob']\n\n\u002F\u002F Filter active users\nconst activeUsers = users.filter(u => u.isActive);\n\n\u002F\u002F reduce: group by property\nconst fruits = ['apple','banana','apple'];\nconst count = fruits.reduce((acc, fruit) => {\n  acc[fruit] = (acc[fruit] || 0) + 1;\n  return acc;\n}, {}); \u002F\u002F { apple:2, banana:1 }\n\n\u002F\u002F Chaining\nconst result = numbers.filter(n => n > 2).map(n => n * 10).reduce((a,b) => a+b, 0);\n```\n\n**Execution Flow:**\nEach method iterates over array indices from 0 to length-1, executes callback for each element, builds result (new array or accumulator) and returns.\n\n**Practical Usage:**\n- Prefer `map`\u002F`filter`\u002F`reduce` over `for` loops for readability and immutability.\n- Use `reduce` for sum, average, flattening, or any transformation to non-array type.\n\n**Interview Insight:**\n`reduce` can implement `map` and `filter`: `arr.map(fn) = arr.reduce((acc,val) => [...acc, fn(val)], [])`. Performance: chaining causes multiple passes; one pass with `reduce` is faster for complex transforms.\n\n**Common Mistakes:**\n- Forgetting to return value in `reduce` accumulator.\n- Mutating original array inside `map`\u002F`filter` (side effects).\n- Using `map` when you don't need a returned array (use `forEach` instead).\n\n**Real-world Example:**\nTransforming API data: `fetch('\u002Fusers').then(res => res.json()).then(users => users.filter(u => u.active).map(u => ({ id: u.id, fullName: u.name })))`.\n\n**Advanced Notes:**\n`reduceRight` reduces from right to left. `flatMap` maps then flattens by one level. These methods skip empty slots (sparse arrays). `Array.from()` creates arrays from iterables with mapping.",[62,63,64,65,66],"arrays","map","filter","reduce","functional",{"id":68,"category":69,"question":70,"answer":71,"level":10,"tags":72},8,"Objects","How do you create and manipulate objects in JavaScript? Explain object literal syntax, property access, and dynamic properties.","**Concept Explanation:**\nObjects are collections of key-value pairs (properties). Created via object literals `{}`, `new Object()`, or `Object.create()`. Properties can be accessed via dot notation or bracket notation. Dynamic properties (computed keys) use brackets.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Object literal\nconst user = {\n  name: 'Alice',\n  age: 25,\n  'favorite color': 'blue' \u002F\u002F quoted key\n};\n\n\u002F\u002F Property access\nconsole.log(user.name);        \u002F\u002F 'Alice' (dot)\nconsole.log(user['age']);      \u002F\u002F 25 (bracket)\nconsole.log(user['favorite color']); \u002F\u002F 'blue'\n\n\u002F\u002F Dynamic properties\nconst key = 'email';\nuser[key] = 'alice@example.com';\n\n\u002F\u002F Shorthand properties\nconst city = 'NYC';\nconst profile = { city }; \u002F\u002F { city: 'NYC' }\n\n\u002F\u002F Method shorthand\nconst obj = {\n  greet() { console.log('Hi'); }\n};\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Computed property names (ES6)\nconst prop = 'age';\nconst person = {\n  name: 'Bob',\n  [prop]: 30,\n  [`${prop}Value`]: 30\n};\n\n\u002F\u002F Property deletion\ndelete person.age;\n\n\u002F\u002F Object spreading (shallow copy)\nconst clone = { ...user };\nconst merged = { ...user, ...person };\n\n\u002F\u002F Property existence\nconsole.log('name' in user);      \u002F\u002F true\nconsole.log(user.hasOwnProperty('name')); \u002F\u002F true\n```\n\n**Execution Flow:**\nObject literals allocate memory, set prototype to `Object.prototype`. Dot notation is faster at runtime, bracket notation allows expressions. Non-existent property access returns `undefined`.\n\n**Practical Usage:**\n- Use dot notation for static, known keys.\n- Use bracket notation for dynamic keys, keys with spaces\u002Fspecial chars.\n- Use optional chaining `obj?.nested?.prop` for safe access.\n\n**Interview Insight:**\nObjects in JavaScript are hash tables (dictionaries). Property keys are strings or Symbols; numbers are converted to strings. Object property order: integer-like keys in ascending order, others in insertion order.\n\n**Common Mistakes:**\n- Accidentally accessing property with dot and dynamic variable: `obj[key]` not `obj.key`.\n- Using `delete` impacts performance; set to `null` or `undefined` instead.\n- Assuming object property iteration order is predictable in older environments.\n\n**Real-world Example:**\nConfiguration objects: `const config = { apiUrl: 'https:\u002F\u002Fapi.example.com', timeout: 5000 }`. Access with `config.apiUrl`.\n\n**Advanced Notes:**\n`Object.freeze()` makes object immutable (shallow). `Object.seal()` prevents additions\u002Fdeletions but allows modifications. `Object.defineProperty()` for fine-grained control (enumerable, writable, configurable).",[73,74,23],"objects","properties",{"id":76,"category":77,"question":78,"answer":79,"level":10,"tags":80},9,"DOM","How do you select and manipulate DOM elements using JavaScript? Explain methods like getElementById, querySelector, and modifying content\u002Fattributes.","**Concept Explanation:**\nDOM (Document Object Model) represents HTML as a tree of nodes. JavaScript provides methods to select elements: `getElementById`, `getElementsByClassName`, `querySelector`, `querySelectorAll`. Manipulation includes changing content (`textContent`, `innerHTML`), attributes (`setAttribute`), styles, and classes.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Selection\nconst header = document.getElementById('main-header');\nconst items = document.getElementsByClassName('item');\nconst firstButton = document.querySelector('.btn'); \u002F\u002F first match\nconst allButtons = document.querySelectorAll('.btn'); \u002F\u002F NodeList\n\n\u002F\u002F Content manipulation\nheader.textContent = 'New Title';\nheader.innerHTML = '\u003Cspan>Bold text\u003C\u002Fspan>';\n\n\u002F\u002F Attributes\nconst img = document.querySelector('img');\nimg.setAttribute('src', 'image.jpg');\nconst src = img.getAttribute('src');\n\n\u002F\u002F Styles\nheader.style.color = 'red';\nheader.style.backgroundColor = 'black';\n\n\u002F\u002F Classes\nheader.classList.add('highlight');\nheader.classList.remove('highlight');\nheader.classList.toggle('active');\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Creating and appending elements\nconst newDiv = document.createElement('div');\nnewDiv.textContent = 'I am new';\ndocument.body.appendChild(newDiv);\n\n\u002F\u002F Removing elements\nconst old = document.getElementById('old');\nold.remove(); \u002F\u002F or parent.removeChild(old)\n\n\u002F\u002F Event listener on selected element\nconst btn = document.querySelector('#myButton');\nbtn.addEventListener('click', () => {\n  alert('Clicked!');\n});\n```\n\n**Execution Flow:**\nDOM methods traverse the tree. `getElementById` is fastest because browser maintains ID index. `querySelector` uses CSS selector engine, slower but flexible. Returns live vs static collections: `getElementsByClassName` returns live HTMLCollection; `querySelectorAll` returns static NodeList.\n\n**Practical Usage:**\n- Prefer `querySelector`\u002F`querySelectorAll` for flexibility and consistency.\n- Use `textContent` over `innerHTML` to avoid XSS risks.\n- Batch DOM updates for performance: use `documentFragment`.\n\n**Interview Insight:**\nLive collections automatically update when DOM changes, which can cause performance issues in loops. Static NodeLists are safer for iteration.\n\n**Common Mistakes:**\n- Using `innerHTML` with user input (XSS vulnerability).\n- Forgetting that `querySelectorAll` returns NodeList (not array) – convert with `Array.from()` or spread `[...nodes]`.\n- Accessing element before DOM ready – use `DOMContentLoaded` event.\n\n**Real-world Example:**\nDynamic to-do list: selecting list container with `querySelector`, creating new list items with `createElement`, appending, adding delete button with event listener.\n\n**Advanced Notes:**\n`Element.insertAdjacentHTML` for efficient HTML insertion without breaking existing references. `MutationObserver` watches DOM changes. `requestAnimationFrame` for animation-friendly DOM updates.",[81,82,83],"dom","selection","manipulation",{"id":85,"category":77,"question":86,"answer":87,"level":10,"tags":88},10,"How does event handling work in JavaScript? Explain addEventListener, event object, and event propagation basics (bubbling and capturing).","**Concept Explanation:**\nEvents are actions (clicks, keypresses) that JavaScript can respond to. `addEventListener` registers handlers. Event object contains details (target, type). Propagation happens in two phases: capturing (down from window to target) and bubbling (up from target to window). By default, handlers run in bubbling phase.\n\n**Syntax Explanation:**\n```javascript\nconst button = document.getElementById('myButton');\n\n\u002F\u002F Basic event listener\nbutton.addEventListener('click', (event) => {\n  console.log('Button clicked');\n  console.log(event.target); \u002F\u002F element that triggered\n  console.log(event.type);   \u002F\u002F 'click'\n});\n\n\u002F\u002F Capturing phase (third parameter true)\nbutton.addEventListener('click', handler, true);\n\n\u002F\u002F Remove listener\nbutton.removeEventListener('click', handler);\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Event propagation example\n\u003Cdiv id=\"parent\">\n  \u003Cbutton id=\"child\">Click\u003C\u002Fbutton>\n\u003C\u002Fdiv>\n\ndocument.getElementById('parent').addEventListener('click', () => {\n  console.log('Parent bubble');\n});\ndocument.getElementById('child').addEventListener('click', (e) => {\n  console.log('Child bubble');\n  e.stopPropagation(); \u002F\u002F prevents bubbling\n});\n\u002F\u002F Clicking child logs: 'Child bubble' only\n\n\u002F\u002F Preventing default\ndocument.querySelector('form').addEventListener('submit', (e) => {\n  e.preventDefault(); \u002F\u002F stops form submission\n});\n```\n\n**Execution Flow:**\n1. Capturing phase: event from window down to target (not used by default).\n2. Target phase: event reaches target element.\n3. Bubbling phase: event propagates back up to window.\n\n**Practical Usage:**\n- Use `event.stopPropagation()` to prevent parent handlers from firing.\n- Use `event.preventDefault()` to cancel default behavior (link navigation, form submit).\n- Event delegation: attach listener to parent, use `event.target` to handle dynamic children.\n\n**Interview Insight:**\nMost libraries (React) use synthetic events. Event delegation improves performance for many similar elements.\n\n**Common Mistakes:**\n- Forgetting to pass function reference (not invocation) to `addEventListener`.\n- Relying on `stopPropagation` when event delegation is a better pattern.\n- Not removing event listeners in long-lived single-page apps (memory leaks).\n\n**Real-world Example:**\nModal close button: `closeBtn.addEventListener('click', () => modal.classList.add('hidden'))`; document click listener to close when clicking outside (check `!modal.contains(event.target)`).\n\n**Advanced Notes:**\nPassive events `{ passive: true }` improve scroll performance. `once: true` auto-removes listener. `AbortController` can remove listeners via signal.",[89,81,90],"events","event-propagation",{"id":92,"category":93,"question":94,"answer":95,"level":10,"tags":96},11,"Asynchronous JavaScript","What are Promises in JavaScript? Explain states (pending, fulfilled, rejected) and how to chain them using .then() and .catch().","**Concept Explanation:**\nA Promise is an object representing eventual completion (or failure) of an asynchronous operation. States: `pending` (initial), `fulfilled` (success), `rejected` (failure). Promises allow chaining with `.then()` for success and `.catch()` for errors, avoiding callback hell.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Creating a Promise\nconst myPromise = new Promise((resolve, reject) => {\n  setTimeout(() => {\n    const success = true;\n    if (success) resolve('Data loaded');\n    else reject('Error occurred');\n  }, 1000);\n});\n\n\u002F\u002F Consuming\nmyPromise\n  .then(result => {\n    console.log(result); \u002F\u002F 'Data loaded'\n    return result.toUpperCase();\n  })\n  .then(processed => {\n    console.log(processed); \u002F\u002F 'DATA LOADED'\n  })\n  .catch(error => {\n    console.error(error);\n  })\n  .finally(() => {\n    console.log('Always runs');\n  });\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Promise chaining with fetch\nfetch('https:\u002F\u002Fapi.example.com\u002Fdata')\n  .then(response => {\n    if (!response.ok) throw new Error('Network error');\n    return response.json();\n  })\n  .then(data => {\n    console.log(data);\n    return processData(data);\n  })\n  .then(result => updateUI(result))\n  .catch(error => showError(error.message));\n\n\u002F\u002F Promise.all (wait for all)\nconst p1 = fetch('\u002Fuser');\nconst p2 = fetch('\u002Fposts');\nPromise.all([p1, p2])\n  .then(([userRes, postsRes]) => Promise.all([userRes.json(), postsRes.json()]))\n  .then(([user, posts]) => console.log(user, posts));\n```\n\n**Execution Flow:**\nPromise constructor executes immediately. `resolve`\u002F`reject` transition state. Handlers in `.then()`\u002F.catch() are placed in microtask queue when promise settles, executed after current synchronous code.\n\n**Practical Usage:**\n- Wrap legacy callbacks (`setTimeout`, `readFile`) into Promises.\n- Chain async operations sequentially.\n- Use `Promise.all` for parallel independent requests, `Promise.race` for timeout patterns.\n\n**Interview Insight:**\nPromise callbacks are microtasks, higher priority than macrotasks (setTimeout). `Promise.resolve()` \u002F `Promise.reject()` create settled promises. `Promise.allSettled()` waits for all regardless of rejection.\n\n**Common Mistakes:**\n- Forgetting to return a promise in `.then()` breaks chaining.\n- Swallowing errors by not having `.catch()` at end.\n- Creating promise constructor unnecessarily (use `async\u002Fawait` or `fetch` instead).\n\n**Real-world Example:**\nLoading user profile and their posts: `Promise.all([fetchUser(), fetchPosts()]).then(([user, posts]) => render(user, posts))`.\n\n**Advanced Notes:**\nUnhandled rejection events (`unhandledrejection`). Promise combinators: `Promise.any()` resolves with first success; `Promise.race()` resolves with first settled. Microtask queue prioritization affects event loop.",[97,98,99],"promises","async","asynchronous",{"id":101,"category":93,"question":102,"answer":103,"level":10,"tags":104},12,"How does async\u002Fawait work in JavaScript? Explain how to handle errors with try\u002Fcatch.","**Concept Explanation:**\n`async` functions return a Promise. `await` pauses execution until Promise resolves, returning the resolved value. Errors are handled with `try\u002Fcatch` blocks, making asynchronous code read like synchronous code.\n\n**Syntax Explanation:**\n```javascript\nasync function fetchData() {\n  try {\n    const response = await fetch('https:\u002F\u002Fapi.example.com\u002Fdata');\n    if (!response.ok) throw new Error('HTTP error');\n    const data = await response.json();\n    console.log(data);\n    return data;\n  } catch (error) {\n    console.error('Fetch failed:', error.message);\n    throw error; \u002F\u002F rethrow if needed\n  } finally {\n    console.log('Cleanup');\n  }\n}\n\n\u002F\u002F Arrow function\nconst getData = async () => {\n  const result = await fetchData();\n  return result;\n};\n\n\u002F\u002F Top-level await (ES2022, modules only)\nconst data = await fetch('\u002Fapi\u002Fconfig');\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Sequential vs parallel\nasync function sequential() {\n  const user = await fetchUser();   \u002F\u002F waits\n  const posts = await fetchPosts(); \u002F\u002F waits for user first\n  return { user, posts };\n}\n\nasync function parallel() {\n  const userPromise = fetchUser();\n  const postsPromise = fetchPosts();\n  const [user, posts] = await Promise.all([userPromise, postsPromise]);\n  return { user, posts };\n}\n\n\u002F\u002F Error handling multiple awaits\nasync function handleMultiple() {\n  try {\n    const result1 = await asyncOp1();\n    const result2 = await asyncOp2(result1);\n    return result2;\n  } catch (err) {\n    \u002F\u002F catches error from either asyncOp1 or asyncOp2\n    console.error(err);\n  }\n}\n```\n\n**Execution Flow:**\nWhen `await` is encountered, function suspends, returns pending promise. When awaited promise settles, function resumes, returns resolved value or throws rejection which can be caught.\n\n**Practical Usage:**\n- Always use `try\u002Fcatch` for error handling unless you want promise rejection to propagate.\n- Combine `async\u002Fawait` with `Promise.all` for parallel operations.\n- Use in loops: `for...of` works, but `forEach` does not await properly.\n\n**Interview Insight:**\n`async\u002Fawait` is syntactic sugar over Promises. Functions marked `async` always return Promise – even if you return a primitive, it's wrapped. Top-level await is only available in ES modules.\n\n**Common Mistakes:**\n- Forgetting `await` before promise – returns promise not value.\n- Using `await` inside `forEach` – doesn't wait; use `for...of` or `Promise.all` with `map`.\n- Not wrapping entire async flow in try\u002Fcatch, causing unhandled rejections.\n\n**Real-world Example:**\nExpress route handler: `app.get('\u002Fuser\u002F:id', async (req, res) => { try { const user = await db.findUser(req.params.id); res.json(user); } catch(e) { res.status(500).send('Error'); } })`.\n\n**Advanced Notes:**\nAsync generator functions (`async function*`) yield promises. Async functions can use `await` with any thenable. Stack traces in async\u002Fawait are better than raw promises.",[105,97,106],"async-await","error-handling",{"id":108,"category":109,"question":110,"answer":111,"level":10,"tags":112},13,"Browser APIs","How do you make HTTP requests using the Fetch API? Explain response handling, JSON parsing, and error handling.","**Concept Explanation:**\nFetch API provides a modern, promise-based way to make HTTP requests. `fetch()` returns a Promise that resolves to a Response object. Response methods like `.json()`, `.text()`, `.blob()` return promises. Errors: fetch only rejects on network failure, not HTTP error status (404, 500).\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Basic GET request\nfetch('https:\u002F\u002Fapi.example.com\u002Fusers')\n  .then(response => {\n    if (!response.ok) {\n      throw new Error(`HTTP error! status: ${response.status}`);\n    }\n    return response.json();\n  })\n  .then(data => console.log(data))\n  .catch(error => console.error('Fetch error:', error));\n\n\u002F\u002F POST request\nfetch('https:\u002F\u002Fapi.example.com\u002Fusers', {\n  method: 'POST',\n  headers: {\n    'Content-Type': 'application\u002Fjson',\n  },\n  body: JSON.stringify({ name: 'John', age: 30 }),\n})\n  .then(res => res.json())\n  .then(data => console.log('Created:', data));\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F async\u002Fawait version with error handling\nasync function fetchUsers() {\n  try {\n    const response = await fetch('https:\u002F\u002Fapi.example.com\u002Fusers');\n    if (!response.ok) {\n      throw new Error(`Status ${response.status}`);\n    }\n    const users = await response.json();\n    return users;\n  } catch (error) {\n    console.error('Network or parsing error:', error);\n    return [];\n  }\n}\n\n\u002F\u002F Request with options\nfetch('\u002Fapi\u002Fdata', {\n  method: 'PUT',\n  headers: { 'Authorization': 'Bearer token' },\n  body: JSON.stringify(data),\n  credentials: 'include', \u002F\u002F send cookies\n  mode: 'cors',\n});\n```\n\n**Execution Flow:**\n`fetch()` returns pending promise. When server responds, promise resolves with Response object. Body methods (.json()) read stream, return another promise that resolves with parsed content.\n\n**Practical Usage:**\n- Always check `response.ok` (status 200-299) to handle HTTP errors.\n- Use `AbortController` to cancel requests (timeouts, component unmount).\n- Combine with `Promise.all` for parallel requests.\n\n**Interview Insight:**\nFetch doesn't reject on HTTP error status because a 404 is still a valid response. Response stream can only be consumed once; clone with `response.clone()` if needed.\n\n**Common Mistakes:**\n- Forgetting to call `.json()` (trying to use response directly).\n- Not handling network failures (offline, DNS error) via `.catch()`.\n- Assuming fetch automatically sends cookies – need `credentials: 'include'`.\n\n**Real-world Example:**\nLoading user list in a component: `useEffect(() => { fetchUsers().then(setUsers); }, [])` with loading\u002Ferror state.\n\n**Advanced Notes:**\nStreaming responses with `response.body` (ReadableStream). `fetch` supports `window` and `worker` contexts. Custom `Request` object: `const req = new Request(url, options); fetch(req)`. No timeout by default; implement with `AbortSignal.timeout()` (newer browsers).",[113,114,115,97],"fetch","http","api",{"id":117,"category":118,"question":119,"answer":120,"level":10,"tags":121},14,"Modules","What are ES6 modules? Explain import and export syntax and how they differ from script tags.","**Concept Explanation:**\nES6 modules (ESM) are JavaScript's native module system using `import` and `export` keywords. Each module has its own scope, dependencies are explicitly declared, and modules are loaded asynchronously by default. This differs from classic script tags which share global scope.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F math.js - named exports\nexport const PI = 3.14159;\nexport function add(a, b) { return a + b; }\nexport class Calculator { \u002F*...*\u002F }\n\n\u002F\u002F app.js - named imports\nimport { PI, add } from '.\u002Fmath.js';\nconsole.log(add(2,3)); \u002F\u002F 5\n\n\u002F\u002F Default export (one per module)\n\u002F\u002F logger.js\nexport default function log(message) {\n  console.log(message);\n}\n\u002F\u002F main.js\nimport log from '.\u002Flogger.js';\n\n\u002F\u002F Combined import\nimport log, { PI, add } from '.\u002Fmodule.js';\n\n\u002F\u002F Namespace import\nimport * as MathUtils from '.\u002Fmath.js';\nMathUtils.add(1,2);\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Dynamic import (lazy loading)\nbutton.addEventListener('click', async () => {\n  const module = await import('.\u002Fheavy-module.js');\n  module.doSomething();\n});\n\n\u002F\u002F HTML usage\n\u003Cscript type=\"module\" src=\"main.js\">\u003C\u002Fscript>\n\u003Cscript nomodule>\u002F\u002F fallback for older browsers\u003C\u002Fscript>\n```\n\n**Execution Flow:**\nModule scripts are deferred by default (download in parallel, execute after parsing). The browser builds module graph, resolves dependencies (once), then evaluates. Imports are hoisted.\n\n**Practical Usage:**\n- Organize code into reusable modules with clear boundaries.\n- Use dynamic import for code splitting (reducing initial load).\n- Prefer named exports for multiple values, default export for main functionality.\n\n**Interview Insight:**\nES modules are strict by default (`'use strict'` automatically). Module specifiers require full file path or package name (no automatic `.js` extension). Imports are live read-only views (changes in exported module reflect).\n\n**Common Mistakes:**\n- Forgetting `type=\"module\"` in script tag, causing module syntax to error.\n- Mixing default and named export importing incorrectly.\n- Trying to use `import` in non-module script (`type=\"module\"` or .mjs).\n\n**Real-world Example:**\nReact app: `import React from 'react'` (default), `import { useState, useEffect } from 'react'` (named).\n\n**Advanced Notes:**\nImport maps control module resolution. Node.js supports ESM with `\"type\": \"module\"` in package.json or `.mjs` extension. Circular imports are allowed but need care. Top-level await only works in modules.",[122,23,123],"modules","import-export",{"id":125,"category":126,"question":127,"answer":128,"level":10,"tags":129},15,"Error Handling","How does error handling work in JavaScript using try, catch, finally, and throw? Give an example with asynchronous code.","**Concept Explanation:**\n`try` block encloses code that may throw an error. `catch` block executes when error occurs. `finally` always executes after try\u002Fcatch. `throw` creates custom errors. For asynchronous code, `try\u002Fcatch` works with `async\u002Fawait`; for promises without await, use `.catch()`.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Synchronous try\u002Fcatch\u002Ffinally\ntry {\n  let result = riskyOperation();\n  console.log(result);\n} catch (error) {\n  console.error('Error caught:', error.message);\n} finally {\n  console.log('Cleanup always runs');\n}\n\n\u002F\u002F Throwing custom errors\nfunction divide(a, b) {\n  if (b === 0) {\n    throw new Error('Division by zero');\n  }\n  return a \u002F b;\n}\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Async\u002Fawait with try\u002Fcatch\nasync function fetchData() {\n  try {\n    const response = await fetch('https:\u002F\u002Fapi.example.com');\n    if (!response.ok) {\n      throw new Error(`HTTP ${response.status}`);\n    }\n    const data = await response.json();\n    return data;\n  } catch (error) {\n    console.error('Fetch failed:', error);\n    \u002F\u002F Re-throw if caller needs to handle\n    throw error;\n  } finally {\n    console.log('Request completed');\n  }\n}\n\n\u002F\u002F Promise chain with .catch()\nfetch('https:\u002F\u002Fapi.example.com')\n  .then(res => res.json())\n  .catch(err => console.error('Network error:', err));\n\n\u002F\u002F Try-catch with JSON parsing\nlet user;\ntry {\n  user = JSON.parse(invalidJSONString);\n} catch (e) {\n  user = { name: 'Guest' }; \u002F\u002F fallback\n}\n```\n\n**Execution Flow:**\nWhen `throw` occurs, JavaScript creates error object and unwinds stack until `catch` block. If no catch, error propagates up. `finally` runs after try\u002Fcatch regardless of error.\n\n**Practical Usage:**\n- Use `try\u002Fcatch` around JSON parsing, I\u002FO, network calls, user input.\n- Always handle promise rejections (unhandled rejection crashes Node.js).\n- Use `finally` for cleanup (close files, hide loaders).\n\n**Interview Insight:**\n`try\u002Fcatch` only catches errors in synchronous code within its block. For promises, only awaited rejections are caught; otherwise use `.catch()`. `try\u002Fcatch` is expensive in performance-critical loops.\n\n**Common Mistakes:**\n- Putting `await` inside try but forgetting that non-awaited promises won't be caught.\n- Empty catch block (`catch(e) {}`) swallowing errors silently.\n- Throwing non-Error objects (throw 'error') loses stack trace.\n\n**Real-world Example:**\nForm submission handler:\n```javascript\nasync function submitForm(formData) {\n  try {\n    showSpinner();\n    const response = await fetch('\u002Fsubmit', { method: 'POST', body: formData });\n    if (!response.ok) throw new Error('Submission failed');\n    await response.json();\n    showSuccess();\n  } catch (err) {\n    showError(err.message);\n  } finally {\n    hideSpinner();\n  }\n}\n```\n\n**Advanced Notes:**\nCustom error classes extending `Error`. Global error handlers: `window.onerror` (browser), `process.on('uncaughtException')` (Node). `error.cause` property for chained errors (ES2022).",[106,130,98],"try-catch",{"id":132,"category":7,"question":133,"answer":134,"level":10,"tags":135},16,"What are template literals in JavaScript? Explain string interpolation, multi-line strings, and tagged templates.","**Concept Explanation:**\nTemplate literals (ES6) are string literals using backticks (\\`) instead of quotes. They support string interpolation with `${expression}`, multi-line strings without escaping, and tagged templates for custom string processing.\n\n**Syntax Explanation:**\n```javascript\nconst name = 'Alice';\nconst age = 30;\n\n\u002F\u002F String interpolation\nconst message = `Hello, my name is ${name} and I am ${age} years old.`;\n\n\u002F\u002F Multi-line strings\nconst multiLine = `\n  This is line 1\n  This is line 2\n  Indentation is preserved\n`;\n\n\u002F\u002F Expression can contain any valid JavaScript\nconst result = `Sum: ${2 + 3}`; \u002F\u002F 'Sum: 5'\nconst conditional = `Access: ${isAdmin ? 'granted' : 'denied'}`;\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Tagged templates (custom processing)\nfunction highlight(strings, ...values) {\n  let result = '';\n  strings.forEach((str, i) => {\n    result += str;\n    if (values[i]) {\n      result += `\u003Cstrong>${values[i]}\u003C\u002Fstrong>`;\n    }\n  });\n  return result;\n}\nconst item = 'JavaScript';\nconst level = 'advanced';\nconst html = highlight`Learn ${item} - ${level} level`;\n\u002F\u002F 'Learn \u003Cstrong>JavaScript\u003C\u002Fstrong> - \u003Cstrong>advanced\u003C\u002Fstrong> level'\n\n\u002F\u002F Raw strings (escape sequences preserved)\nconst path = String.raw`C:\\Users\\name\\file.txt`;\nconsole.log(path); \u002F\u002F 'C:\\Users\\name\\file.txt' (backslashes preserved)\n\n\u002F\u002F Nesting templates\nconst icon = 'star';\nconst tooltip = `Icon: ${`\u003Ci class=\"icon-${icon}\">\u003C\u002Fi>`}`;\n```\n\n**Execution Flow:**\nTemplate literal is parsed: expressions inside `${}` are evaluated, converted to strings (using `toString()`), then concatenated with static parts.\n\n**Practical Usage:**\n- Build dynamic HTML strings safely (but beware XSS).\n- Create readable multi-line SQL queries, CSS, or error messages.\n- Tagged templates for DSLs (styled-components in React, graphql tag).\n\n**Interview Insight:**\nTagged templates receive strings array (raw via `strings.raw`). The tag function can return any value, not just string. `String.raw` is a built-in tag that doesn't interpret escape sequences.\n\n**Common Mistakes:**\n- Using quotes inside template literals without escaping (backticks inside need backslash).\n- Assuming whitespace in multi-line strings is not significant.\n- Not realizing expressions are evaluated immediately, not lazily.\n\n**Real-world Example:**\nGenerating email templates: `sendEmail({ body: `Dear ${user.name},\\n\\nYour order ${order.id} is confirmed.` })`.\n\n**Advanced Notes:**\nTagged template literals can be used for localization, safe HTML escaping, or query builders. The raw property is accessed via `strings.raw[index]`.",[136,23,137],"template-literals","strings",{"id":139,"category":17,"question":140,"answer":141,"level":10,"tags":142},17,"What is destructuring assignment in JavaScript? Provide examples for arrays and objects.","**Concept Explanation:**\nDestructuring assignment allows unpacking values from arrays or properties from objects into distinct variables. It provides concise syntax and can set default values, rename variables, and handle nested structures.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Array destructuring\nconst colors = ['red', 'green', 'blue'];\nconst [first, second, third] = colors;\nconsole.log(first); \u002F\u002F 'red'\n\n\u002F\u002F Skipping elements\nconst [, secondColor] = colors;\nconsole.log(secondColor); \u002F\u002F 'green'\n\n\u002F\u002F Object destructuring\nconst user = { name: 'Alice', age: 25, city: 'NYC' };\nconst { name, age } = user;\nconsole.log(name, age); \u002F\u002F 'Alice' 25\n\n\u002F\u002F Renaming\nconst { name: userName, age: userAge } = user;\nconsole.log(userName); \u002F\u002F 'Alice'\n\n\u002F\u002F Default values\nconst { role = 'guest' } = user;\nconsole.log(role); \u002F\u002F 'guest'\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Nested destructuring\nconst person = {\n  id: 1,\n  address: { street: 'Main St', zip: 12345 }\n};\nconst { address: { street, zip } } = person;\nconsole.log(street); \u002F\u002F 'Main St'\n\n\u002F\u002F Function parameters destructuring\nfunction displayUser({ name, age = 'Unknown' }) {\n  console.log(`${name}, ${age}`);\n}\ndisplayUser({ name: 'Bob' }); \u002F\u002F 'Bob, Unknown'\n\n\u002F\u002F Swapping variables\nlet a = 1, b = 2;\n[a, b] = [b, a];\nconsole.log(a, b); \u002F\u002F 2, 1\n\n\u002F\u002F Rest with destructuring\nconst [head, ...tail] = [1, 2, 3, 4];\nconsole.log(head); \u002F\u002F 1\nconsole.log(tail); \u002F\u002F [2,3,4]\n\nconst { id, ...rest } = person;\nconsole.log(rest); \u002F\u002F { address: {...} }\n```\n\n**Execution Flow:**\nDestructuring uses iterable protocol for arrays (anything iterable works: Set, Map, generators). Objects use property matching. Values are assigned right-to-left.\n\n**Practical Usage:**\n- Extract values from API responses or React props.\n- Swap variables without temporary variable.\n- Provide default values for missing properties.\n\n**Interview Insight:**\nObject destructuring uses `[[Enumerable]]` own properties. Parentheses may be needed when destructuring pre-declared variables without `let`\u002F`const`: `({ a, b } = obj)`. Arrays destructuring works with any iterable.\n\n**Common Mistakes:**\n- Confusing array destructuring with object (using `{}` for array).\n- Forgetting default values only apply if property is `undefined` (not `null`).\n- Missing parentheses when assigning to existing variables without declaration.\n\n**Real-world Example:**\nReact hooks: `const [count, setCount] = useState(0)`. Import specific functions: `import { useState, useEffect } from 'react'`.\n\n**Advanced Notes:**\nDestructuring can use computed property names: `const { [key]: value } = obj`. Pattern can be arbitrarily nested. `undefined` triggers default values.",[143,23,73,62],"destructuring",{"id":145,"category":17,"question":146,"answer":147,"level":10,"tags":148},18,"Explain the spread and rest operators (...) in JavaScript. How are they used in arrays, objects, and function parameters?","**Concept Explanation:**\nThe `...` operator serves two purposes: **spread** expands elements (iterable) into individual items; **rest** collects multiple elements into an array or object. Context determines which: in function parameters or destructuring left side it's rest; in array literals, function calls, or object literals it's spread.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Spread in arrays\nconst arr1 = [1, 2, 3];\nconst arr2 = [4, 5, 6];\nconst combined = [...arr1, ...arr2]; \u002F\u002F [1,2,3,4,5,6]\n\n\u002F\u002F Spread in objects (shallow copy)\nconst obj1 = { a: 1, b: 2 };\nconst obj2 = { c: 3 };\nconst merged = { ...obj1, ...obj2 }; \u002F\u002F { a:1, b:2, c:3 }\n\n\u002F\u002F Rest in function parameters\nfunction sum(...numbers) {\n  return numbers.reduce((acc, n) => acc + n, 0);\n}\nsum(1, 2, 3, 4); \u002F\u002F 10\n\n\u002F\u002F Rest in array destructuring\nconst [first, second, ...remaining] = [10, 20, 30, 40];\nconsole.log(remaining); \u002F\u002F [30, 40]\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Spread for function arguments\nconst nums = [5, 10, 15];\nMath.max(...nums); \u002F\u002F 15\n\n\u002F\u002F Copying arrays (shallow)\nconst original = [1, 2, 3];\nconst copy = [...original];\n\n\u002F\u002F Converting NodeList to array\nconst divs = [...document.querySelectorAll('div')];\n\n\u002F\u002F Rest in object destructuring (ES2018)\nconst user = { name: 'Alice', age: 30, city: 'NYC', role: 'admin' };\nconst { name, ...details } = user;\nconsole.log(name);    \u002F\u002F 'Alice'\nconsole.log(details); \u002F\u002F { age:30, city:'NYC', role:'admin' }\n\n\u002F\u002F Spread with strings\nconst chars = [...'hello']; \u002F\u002F ['h','e','l','l','o']\n```\n\n**Execution Flow:**\nSpread iterates over iterable properties (for arrays) or enumerable own properties (for objects). Rest syntax collects unassigned elements into a new array\u002Fobject.\n\n**Practical Usage:**\n- Combine arrays or objects immutably (Redux, React state).\n- Pass array elements as function arguments.\n- Collect remaining arguments in variadic functions.\n\n**Interview Insight:**\nSpread for objects (ES2018) creates shallow copy; nested objects are still referenced. Spread is often used in React for state updates: `setState(prev => ({ ...prev, newProp: value }))`.\n\n**Common Mistakes:**\n- Assuming spread creates deep copy (nested objects mutated).\n- Using rest in object destructuring at non-last position (must be last).\n- Spreading non-iterable values into array (TypeError).\n\n**Real-world Example:**\nImmutable update in Redux reducer: `return { ...state, loading: false, data: [...state.data, newItem] }`.\n\n**Advanced Notes:**\nSpread with `Array.from()` similar. Spread performance okay for small\u002Fmedium arrays. Rest parameters are true arrays (unlike `arguments` object). Object rest\u002Fspread copies enumerable own properties, not prototype.",[149,150,23,62,73],"spread","rest",{"id":152,"category":109,"question":153,"answer":154,"level":10,"tags":155},19,"How does localStorage and sessionStorage work in web browsers? Explain use cases and limitations.","**Concept Explanation:**\nWeb Storage API provides key-value storage in the browser. `localStorage` persists until explicitly cleared, surviving browser restarts. `sessionStorage` persists only for the current tab\u002Fsession, cleared when tab closes. Both store strings (convert other types manually).\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Storing data\nlocalStorage.setItem('theme', 'dark');\nsessionStorage.setItem('token', 'abc123');\n\n\u002F\u002F Retrieving\nconst theme = localStorage.getItem('theme'); \u002F\u002F 'dark' or null\n\n\u002F\u002F Removing\nlocalStorage.removeItem('theme');\nlocalStorage.clear(); \u002F\u002F removes all\n\n\u002F\u002F Storing objects (need JSON)\nconst user = { name: 'Alice' };\nlocalStorage.setItem('user', JSON.stringify(user));\nconst storedUser = JSON.parse(localStorage.getItem('user'));\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Checking availability\nif (typeof Storage !== 'undefined') {\n  \u002F\u002F Storage supported\n}\n\n\u002F\u002F Listening to storage changes (cross-tab)\nwindow.addEventListener('storage', (event) => {\n  console.log(`Key ${event.key} changed from ${event.oldValue} to ${event.newValue}`);\n  \u002F\u002F Only fires for changes in other tabs (not same tab)\n});\n\n\u002F\u002F Session storage for form draft\nconst draftKey = `form_${formId}`;\nfunction saveDraft(data) {\n  sessionStorage.setItem(draftKey, JSON.stringify(data));\n}\nfunction loadDraft() {\n  const saved = sessionStorage.getItem(draftKey);\n  return saved ? JSON.parse(saved) : null;\n}\n```\n\n**Practical Usage:**\n- `localStorage`: user preferences, theme, offline data, cached responses.\n- `sessionStorage`: sensitive temporary data (one-time tokens), form drafts that shouldn't survive session.\n\n**Interview Insight:**\nStorage limit ~5-10MB per origin. Synchronous API (blocks main thread). For larger\u002Fasync storage use IndexedDB. Private browsing mode may throw `QuotaExceededError`.\n\n**Common Mistakes:**\n- Storing sensitive data (XSS can read localStorage).\n- Assuming synchronous getItem is fast for large data.\n- Not handling `QuotaExceededError` (try\u002Fcatch).\n\n**Real-world Example:**\nE-commerce cart: `localStorage.setItem('cart', JSON.stringify(cartItems))` to persist across page reloads. Checkout reads from localStorage to restore cart.\n\n**Advanced Notes:**\n`StorageEvent` only fires for changes from other documents\u002Ftabs. Web Storage is synchronous and blocks rendering; for large writes consider `requestIdleCallback`. Storage API is not available in Web Workers.",[156,157,158,159],"localstorage","sessionstorage","browser-api","storage",{"id":161,"category":7,"question":162,"answer":163,"level":10,"tags":164},20,"Compare different looping mechanisms in JavaScript: for, for...of, for...in, forEach, and while loops.","**Concept Explanation:**\n- `for`: classic loop with initialization, condition, increment.\n- `for...in`: iterates over enumerable property keys (including prototype).\n- `for...of`: iterates over iterable values (arrays, strings, maps, sets).\n- `forEach`: array method, executes callback for each element.\n- `while`: condition-based loop, useful when iterations unknown.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F for\nfor (let i = 0; i \u003C 5; i++) {\n  console.log(i);\n}\n\n\u002F\u002F for...of (values)\nconst arr = [10, 20, 30];\nfor (const value of arr) {\n  console.log(value); \u002F\u002F 10,20,30\n}\n\n\u002F\u002F for...in (keys)\nconst obj = { a: 1, b: 2 };\nfor (const key in obj) {\n  console.log(key, obj[key]);\n}\n\n\u002F\u002F forEach\narr.forEach((value, index) => {\n  console.log(index, value);\n});\n\n\u002F\u002F while\nlet i = 0;\nwhile (i \u003C 5) {\n  console.log(i);\n  i++;\n}\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F for...of with strings\nfor (const char of 'hello') {\n  console.log(char); \u002F\u002F 'h','e','l','l','o'\n}\n\n\u002F\u002F for...in with array (not recommended)\nArray.prototype.extra = 'bad';\nconst nums = [1,2];\nfor (const i in nums) {\n  console.log(i); \u002F\u002F '0','1','extra' (includes prototype)\n}\n\n\u002F\u002F Breaking loops\nfor (const val of arr) {\n  if (val === 20) break; \u002F\u002F works\n}\n\u002F\u002F forEach cannot break (use some\u002Fevery instead)\n\n\u002F\u002F Map vs forEach\nconst doubled = [];\narr.forEach(v => doubled.push(v * 2)); \u002F\u002F side effect\nconst doubledMap = arr.map(v => v * 2); \u002F\u002F functional\n```\n\n**Practical Usage:**\n- Use `for...of` for most array iterations (clean, supports break\u002Fcontinue).\n- Use `for` with index when needing index arithmetic or performance critical.\n- Avoid `for...in` for arrays (use `for...of` or `.forEach`).\n- Use `while` for unknown iteration count (e.g., reading stream).\n\n**Interview Insight:**\n`for...in` iterates over enumerable properties, including inherited ones. Use `hasOwnProperty` check if needed. `for...of` works on any iterable (implement `[Symbol.iterator]`).\n\n**Common Mistakes:**\n- Using `for...in` on arrays (order not guaranteed, includes prototype).\n- Trying to break from `forEach` (can't; use `for...of` or `some`).\n- Forgetting that `for...of` doesn't give index directly (use `.entries()`).\n\n**Real-world Example:**\nProcessing API pagination with while: `while (hasNextPage) { const data = await fetchPage(page); process(data); page++ }`.\n\n**Advanced Notes:**\n`for await...of` for asynchronous iterables. Performance: `for` and `while` fastest, `forEach` slightly slower due to function call overhead. `for...of` with arrays is optimized in modern engines.",[165,166,167,168,169],"loops","iteration","for-of","for-in","foreach",{"id":171,"category":35,"question":172,"answer":173,"level":10,"tags":174},21,"What is the 'this' keyword in JavaScript? How does its value differ in global scope, function context, and arrow functions?","**Concept Explanation:**\n`this` is a special keyword that refers to the execution context. Its value depends on how a function is called (not where defined, except arrow functions). Global `this` is `window` (browser) or `global` (Node). In strict mode, function `this` defaults to `undefined`.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Global scope\nconsole.log(this); \u002F\u002F window (browser), global (Node)\n\n\u002F\u002F Regular function (non-strict)\nfunction showThis() {\n  console.log(this); \u002F\u002F window (global object)\n}\nshowThis();\n\n\u002F\u002F Strict mode\nfunction strictThis() {\n  'use strict';\n  console.log(this); \u002F\u002F undefined\n}\nstrictThis();\n\n\u002F\u002F Method call\nconst obj = {\n  name: 'MyObj',\n  log() {\n    console.log(this.name); \u002F\u002F 'MyObj' (obj)\n  }\n};\nobj.log();\n\n\u002F\u002F Arrow function (lexical this)\nconst arrowObj = {\n  name: 'Arrow',\n  log: () => console.log(this.name) \u002F\u002F this from outer scope\n};\narrowObj.log(); \u002F\u002F undefined or window.name\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F 'this' with call\u002Fapply\u002Fbind\nfunction greet(greeting) {\n  console.log(`${greeting}, ${this.name}`);\n}\nconst user = { name: 'Alice' };\ngreet.call(user, 'Hello'); \u002F\u002F 'Hello, Alice'\ngreet.apply(user, ['Hi']); \u002F\u002F 'Hi, Alice'\nconst boundGreet = greet.bind(user);\nboundGreet('Hey'); \u002F\u002F 'Hey, Alice'\n\n\u002F\u002F Constructor function\nfunction Person(name) {\n  this.name = name;\n}\nconst p = new Person('Bob');\nconsole.log(p.name); \u002F\u002F 'Bob' (this refers to new instance)\n\n\u002F\u002F Event handler this\nbutton.addEventListener('click', function() {\n  console.log(this); \u002F\u002F button element\n});\n```\n\n**Practical Usage:**\n- Use arrow functions in callbacks to preserve surrounding `this`.\n- Use `bind` for React class component event handlers (pre-hooks).\n- `this` in object methods refers to the object.\n\n**Interview Insight:**\n`this` is determined at call-time: default binding (global\u002Fundefined), implicit binding (object), explicit binding (call\u002Fapply\u002Fbind), new binding (constructor). Arrow functions inherit `this` from enclosing lexical scope.\n\n**Common Mistakes:**\n- Losing `this` when passing method as callback (`setTimeout(obj.method, 1000)` loses `this`).\n- Expecting arrow function to have its own `this` (it doesn't).\n- Forgetting `new` with constructor causes `this` to point to global.\n\n**Real-world Example:**\nReact class component: `onClick={this.handleClick.bind(this)}` or use arrow class property: `handleClick = () => { ... }`.\n\n**Advanced Notes:**\n`this` in event handlers: use `e.currentTarget` to refer to bound element. The `this` in eval is same as calling context. `this` in `setTimeout` with arrow function uses lexical scope.",[175,176,39,40],"this","context",{"id":178,"category":69,"question":179,"answer":180,"level":10,"tags":181},22,"How do you parse and stringify JSON in JavaScript? Explain JSON.parse() and JSON.stringify() with examples.","**Concept Explanation:**\nJSON (JavaScript Object Notation) is a lightweight data format. `JSON.parse()` converts JSON string to JavaScript object; `JSON.stringify()` converts JS value to JSON string. Both handle `null`, booleans, numbers, strings, arrays, and plain objects (no functions, `undefined`, symbols).\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Parse JSON string to object\nconst jsonString = '{\"name\":\"Alice\",\"age\":30}';\nconst user = JSON.parse(jsonString);\nconsole.log(user.name); \u002F\u002F 'Alice'\n\n\u002F\u002F Stringify object to JSON\nconst obj = { name: 'Bob', age: 25, isActive: true };\nconst json = JSON.stringify(obj);\nconsole.log(json); \u002F\u002F '{\"name\":\"Bob\",\"age\":25,\"isActive\":true}'\n\n\u002F\u002F Pretty print (spacing)\nconst pretty = JSON.stringify(obj, null, 2);\n\u002F* {\n  \"name\": \"Bob\",\n  \"age\": 25,\n  \"isActive\": true\n} *\u002F\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Handling circular references (will throw error)\nconst circular = { self: null };\ncircular.self = circular;\n\u002F\u002F JSON.stringify(circular); \u002F\u002F TypeError\n\n\u002F\u002F Using replacer function (filter\u002Ftransform)\nconst data = { name: 'Alice', password: 'secret', age: 30 };\nconst safeJson = JSON.stringify(data, (key, value) => {\n  if (key === 'password') return undefined;\n  return value;\n}); \u002F\u002F '{\"name\":\"Alice\",\"age\":30}'\n\n\u002F\u002F Using reviver function in parse\nconst jsonWithDate = '{\"date\":\"2025-01-01T00:00:00Z\"}';\nconst parsed = JSON.parse(jsonWithDate, (key, value) => {\n  if (key === 'date') return new Date(value);\n  return value;\n});\nconsole.log(parsed.date.getFullYear()); \u002F\u002F 2025\n\n\u002F\u002F toJSON method\nconst product = {\n  name: 'Laptop',\n  price: 999,\n  toJSON() {\n    return { name: this.name, priceUSD: this.price };\n  }\n};\nconsole.log(JSON.stringify(product)); \u002F\u002F '{\"name\":\"Laptop\",\"priceUSD\":999}'\n```\n\n**Practical Usage:**\n- Send\u002Freceive data from APIs (fetch response.json).\n- Store complex data in localStorage.\n- Deep copy simple objects: `const copy = JSON.parse(JSON.stringify(obj))` (limitations).\n\n**Interview Insight:**\n`JSON.stringify` ignores functions, `undefined`, symbols; `NaN`, `Infinity` become `null`. Use replacer to customize. `JSON.parse` throws `SyntaxError` on invalid JSON – always wrap in `try\u002Fcatch`.\n\n**Common Mistakes:**\n- Forgetting to parse response when using fetch (response.json() does it).\n- Using `JSON.stringify` for deep cloning (fails with Dates, RegExp, undefined, functions, circular references).\n- Not handling `JSON.parse` errors for untrusted input.\n\n**Real-world Example:**\nStoring user preferences: `localStorage.setItem('settings', JSON.stringify(settings)); const saved = JSON.parse(localStorage.getItem('settings') || '{}');`.\n\n**Advanced Notes:**\n`JSON.stringify` second argument can be array of allowed properties. Third argument is spacing (number or string). `JSON.parse` reviver can transform values (e.g., revive Dates). `BigInt` not supported.",[182,183,184,185],"json","parse","stringify","serialization",{"id":187,"category":7,"question":188,"answer":189,"level":10,"tags":190},23,"Explain explicit and implicit type conversion in JavaScript. Provide examples of converting to string, number, and boolean.","**Concept Explanation:**\nImplicit conversion (coercion) happens automatically when operators or contexts expect a different type. Explicit conversion is done manually using functions like `String()`, `Number()`, `Boolean()`. JavaScript is loosely typed, leading to both convenience and pitfalls.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Implicit conversion (coercion)\nconst sum = '5' + 3;     \u002F\u002F '53' (number coerced to string)\nconst diff = '10' - 2;   \u002F\u002F 8 (string coerced to number)\nconst bool = !'hello';   \u002F\u002F false (string to boolean)\n\n\u002F\u002F Explicit conversion\nString(123);        \u002F\u002F '123'\nNumber('456');      \u002F\u002F 456\nBoolean(0);         \u002F\u002F false\n\n\u002F\u002F Using constructors\nnew Number('5').valueOf(); \u002F\u002F 5 (but not recommended)\n\n\u002F\u002F Idiomatic conversions\nconst toNum = +'123';      \u002F\u002F 123 (unary plus)\nconst toStr = 123 + '';    \u002F\u002F '123'\nconst toBool = !!value;    \u002F\u002F boolean conversion\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F String conversion\nString(null);            \u002F\u002F 'null'\nString(undefined);       \u002F\u002F 'undefined'\nString(true);            \u002F\u002F 'true'\n[1,2].toString();        \u002F\u002F '1,2'\n({}).toString();         \u002F\u002F '[object Object]'\n\n\u002F\u002F Number conversion\nNumber('  42  ');        \u002F\u002F 42 (trims)\nNumber('42px');          \u002F\u002F NaN\nNumber(true);            \u002F\u002F 1\nNumber(false);           \u002F\u002F 0\nNumber(null);            \u002F\u002F 0\nNumber(undefined);       \u002F\u002F NaN\nparseInt('42px', 10);    \u002F\u002F 42 (parses until non-digit)\nparseFloat('3.14em');    \u002F\u002F 3.14\n\n\u002F\u002F Boolean conversion (falsy values: false,0,'',null,undefined,NaN)\nBoolean('hello');        \u002F\u002F true\nBoolean('');             \u002F\u002F false\nBoolean([]);             \u002F\u002F true (array is object, truthy)\nBoolean({});             \u002F\u002F true\n```\n\n**Practical Usage:**\n- Explicit conversion makes intent clear and avoids bugs.\n- Use `Number.isNaN()` to check NaN.\n- Use `parseInt` with radix for base conversion.\n\n**Interview Insight:**\n`==` operator triggers coercion; `===` avoids it. The addition operator (`+`) favors string concatenation if either operand is string. Other arithmetic operators coerce to numbers.\n\n**Common Mistakes:**\n- Relying on `'5' - 1` but `'5' + 1` produces different result.\n- Forgetting that `typeof NaN` is 'number'.\n- Comparing `null` with `0` using `>=` – `null >= 0` true, `null == 0` false.\n\n**Real-world Example:**\nForm input values are strings; explicit conversion needed: `const age = Number(input.value); if (isNaN(age)) showError('Invalid number');`.\n\n**Advanced Notes:**\n`Symbol.toPrimitive` controls conversion for objects. `==` algorithm (Abstract Equality) uses `ToPrimitive` for objects, comparing primitives. BigInt conversion behaves specially.",[191,46,192],"type-conversion","casting",{"id":194,"category":35,"question":195,"answer":196,"level":10,"tags":197},24,"What is a closure in JavaScript? Provide a simple example and explain lexical scoping.","**Concept Explanation:**\nA closure is a function that retains access to its lexical scope (variables from outer function) even after the outer function has finished executing. Closures are created every time a function is defined, allowing data privacy and partial application.\n\n**Syntax Explanation:**\n```javascript\nfunction outer() {\n  let count = 0;\n  \n  function inner() {\n    count++;\n    console.log(count);\n  }\n  \n  return inner;\n}\n\nconst increment = outer();\nincrement(); \u002F\u002F 1\nincrement(); \u002F\u002F 2\n\u002F\u002F inner function 'remembers' count variable\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Private variables (module pattern)\nfunction createCounter(initial = 0) {\n  let value = initial;\n  return {\n    increment() { value++; return value; },\n    decrement() { value--; return value; },\n    getValue() { return value; }\n  };\n}\nconst counter = createCounter(10);\ncounter.increment(); \u002F\u002F 11\n\u002F\u002F Cannot directly access 'value'\n\n\u002F\u002F Closure in loops (classic issue and fix)\nfor (var i = 0; i \u003C 3; i++) {\n  setTimeout(() => console.log(i), 100); \u002F\u002F 3,3,3\n}\nfor (let i = 0; i \u003C 3; i++) {\n  setTimeout(() => console.log(i), 100); \u002F\u002F 0,1,2 (let block scope)\n}\n\u002F\u002F Using closure with var\nfor (var i = 0; i \u003C 3; i++) {\n  ((j) => setTimeout(() => console.log(j), 100))(i); \u002F\u002F 0,1,2\n}\n\n\u002F\u002F Function factories\nfunction multiplier(factor) {\n  return (x) => x * factor;\n}\nconst double = multiplier(2);\nconsole.log(double(5)); \u002F\u002F 10\n```\n\n**Execution Flow:**\nWhen `outer` is called, a new lexical environment is created. `inner` function references this environment. When `outer` returns, its environment is not garbage collected because `inner` still holds a reference – forming closure.\n\n**Practical Usage:**\n- Data encapsulation (private variables).\n- Event handlers and callbacks that need access to outer variables.\n- Memoization and caching.\n- Partial application and currying.\n\n**Interview Insight:**\nClosures are fundamental to JavaScript's functional nature. Every function in JavaScript is a closure (captures its lexical environment). Memory leaks can happen if closures unintentionally retain large objects.\n\n**Common Mistakes:**\n- Creating accidental closures in loops (old var issue).\n- Overusing closures leading to memory retention.\n- Expecting closure to capture current value of variable (captures variable reference, not value).\n\n**Real-world Example:**\nReact `useEffect` capture current props\u002Fstate. Debounce function using closure to preserve timer: `function debounce(fn, delay) { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); } }`.\n\n**Advanced Notes:**\nClosures and garbage collection: modern engines can optimize (escape analysis). Use `WeakRef` and `FinalizationRegistry` for advanced memory management. Closures appear in module systems (CommonJS, ES modules).",[198,22,199],"closures","lexical-scoping",{"id":201,"category":93,"question":202,"answer":203,"level":10,"tags":204},25,"How do setTimeout and setInterval work in JavaScript? Explain their asynchronous nature and how to clear them.","**Concept Explanation:**\n`setTimeout` schedules a function to execute after a delay (in milliseconds), `setInterval` repeatedly executes with fixed delay. Both are asynchronous; they don't block the main thread. Callbacks are placed in task queue and executed after current call stack is empty.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F setTimeout (executes once)\nconst timeoutId = setTimeout(() => {\n  console.log('Executed after 1000ms');\n}, 1000);\n\n\u002F\u002F Clear timeout\nclearTimeout(timeoutId);\n\n\u002F\u002F setInterval (repeats)\nlet counter = 0;\nconst intervalId = setInterval(() => {\n  counter++;\n  console.log(`Tick ${counter}`);\n  if (counter === 5) clearInterval(intervalId);\n}, 1000);\n\n\u002F\u002F Zero delay (execute as soon as possible)\nsetTimeout(() => console.log('Task'), 0);\nconsole.log('First'); \u002F\u002F 'First', then 'Task'\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Delay with parameters\nsetTimeout((name, age) => {\n  console.log(`Hello ${name}, age ${age}`);\n}, 1000, 'Alice', 30);\n\n\u002F\u002F Recursive setTimeout (preferred over setInterval)\nfunction repeat(count) {\n  console.log('Action');\n  if (count > 1) setTimeout(() => repeat(count - 1), 1000);\n}\nrepeat(5); \u002F\u002F better for variable intervals\n\n\u002F\u002F setInterval drift demonstration\nlet start = Date.now();\nsetInterval(() => {\n  console.log(`Elapsed: ${Date.now() - start}ms`); \u002F\u002F drift accumulates\n}, 1000);\n\n\u002F\u002F Debounce with setTimeout\nfunction debounce(fn, delay) {\n  let timer;\n  return (...args) => {\n    clearTimeout(timer);\n    timer = setTimeout(() => fn(...args), delay);\n  };\n}\n```\n\n**Execution Flow:**\n1. `setTimeout\u002FsetInterval` registers callback with timer API (provided by browser\u002FNode).\n2. After delay, callback is added to task queue (macrotask).\n3. Event loop processes call stack, then picks next macrotask.\n4. Timing not guaranteed if call stack is busy; minimum delay is enforced.\n\n**Practical Usage:**\n- Delaying actions (tooltip hide, search debounce).\n- Animations (prefer `requestAnimationFrame`).\n- Polling (use `setInterval` or recursive `setTimeout`).\n\n**Interview Insight:**\n`setTimeout(fn, 0)` doesn't execute immediately; it queues callback. Minimum delay is 4ms for nested timers (clamped). `setInterval` ignores callback execution time; if callback takes longer than interval, next call may queue immediately, causing overlapping.\n\n**Common Mistakes:**\n- Forgetting to clear intervals on component unmount (memory leaks).\n- Assuming exact timing (not reliable).\n- Using `setInterval` for animation (janky, use `requestAnimationFrame`).\n\n**Real-world Example:**\nAuto-save form: `const saveTimer = setTimeout(saveDraft, 3000);` on input; clear previous timer before setting new.\n\n**Advanced Notes:**\n`setTimeout`\u002F`setInterval` have minimum delays (browser: 4ms after 5 nested; Node: 1ms). `clearTimeout`\u002F`clearInterval` invalidate IDs. Use `AbortSignal` to clear timeouts in modern code. For accurate intervals, use recursive `setTimeout` with offset calculation.",[205,206,98,207],"settimeout","setinterval","timers",[209,217,227,235,243,252,262,271,280,288,295,303,311,318,326,332,340,347,355,362],{"id":210,"category":211,"question":212,"answer":213,"level":214,"tags":215},26,"Closures & Scope","What are closures in JavaScript? Explain how they work with practical examples and discuss memory implications.","**Concept Explanation:**\nA closure is a function that retains access to its lexical scope (variables from an outer function) even after the outer function has finished executing. Closures are created automatically when a function is defined, enabling data privacy, partial application, and stateful functions.\n\n**Syntax Explanation:**\n```javascript\nfunction outer() {\n  let count = 0;\n  return function inner() {\n    count++;\n    return count;\n  };\n}\nconst increment = outer();\nconsole.log(increment()); \u002F\u002F 1\nconsole.log(increment()); \u002F\u002F 2\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Module pattern (data hiding)\nfunction createBankAccount(initialBalance) {\n  let balance = initialBalance;\n  return {\n    deposit(amount) {\n      balance += amount;\n      return balance;\n    },\n    withdraw(amount) {\n      if (amount > balance) throw new Error('Insufficient funds');\n      balance -= amount;\n      return balance;\n    },\n    getBalance() { return balance; }\n  };\n}\nconst account = createBankAccount(100);\naccount.deposit(50); \u002F\u002F 150\nconsole.log(account.balance); \u002F\u002F undefined (private)\n\n\u002F\u002F Closure in loops (fixing var issue)\nfor (var i = 0; i \u003C 3; i++) {\n  ((j) => setTimeout(() => console.log(j), 100))(i);\n}\n\n\u002F\u002F Memoization with closure\nfunction memoize(fn) {\n  const cache = new Map();\n  return function(...args) {\n    const key = JSON.stringify(args);\n    if (cache.has(key)) return cache.get(key);\n    const result = fn(...args);\n    cache.set(key, result);\n    return result;\n  };\n}\nconst slowSquare = (x) => { console.log('computing'); return x * x; };\nconst memoizedSquare = memoize(slowSquare);\nmemoizedSquare(5); \u002F\u002F computes\nmemoizedSquare(5); \u002F\u002F returns from cache\n```\n\n**Execution Flow:**\nWhen `outer` is invoked, a new lexical environment is created. `inner` function references this environment. After `outer` returns, its environment remains alive because `inner` still holds a reference. This referenced environment is the closure.\n\n**Practical Usage:**\n- Data encapsulation (private variables).\n- Event handlers and callbacks that need access to outer scope.\n- Function factories and currying.\n- Memoization and caching.\n\n**Interview Insight:**\nEvery function in JavaScript is a closure. Closures capture variable references, not values. This is why the classic loop issue occurs with `var`. Modern engines optimize closures to avoid memory leaks unless variables are retained unnecessarily.\n\n**Common Mistakes:**\n- Creating closures in loops without block scope (using `let` solves it).\n- Expecting closure to capture current value (captures reference).\n- Unintentionally retaining large objects in closure, preventing garbage collection.\n\n**Real-world Example:**\nReact hooks rely on closures: `useEffect` captures props\u002Fstate from the render where it was defined. Debounce\u002Fthrottle implementations use closures to preserve timer references.\n\n**Advanced Notes:**\nClosures and garbage collection: A closure retains the entire lexical environment, not just the used variables (though engines may optimize via escape analysis). `WeakRef` and `FinalizationRegistry` can help manage advanced scenarios. Closures are fundamental to functional programming patterns in JavaScript.","intermediate",[198,22,216,199],"memory",{"id":218,"category":219,"question":220,"answer":221,"level":214,"tags":222},27,"JavaScript Internals","Explain the prototype chain in JavaScript. How does prototypal inheritance differ from classical inheritance?","**Concept Explanation:**\nPrototypal inheritance is JavaScript's object-oriented model where objects inherit directly from other objects. Each object has an internal `[[Prototype]]` link (accessed via `__proto__` or `Object.getPrototypeOf`). When accessing a property, JavaScript traverses the prototype chain until found or until `null`. This differs from classical inheritance (classes inheriting from classes).\n\n**Syntax Explanation:**\n```javascript\nconst parent = { name: 'Parent', greet() { return `Hi, I'm ${this.name}`; } };\nconst child = Object.create(parent);\nchild.name = 'Child';\nconsole.log(child.greet()); \u002F\u002F 'Hi, I'm Child' (method from parent)\nconsole.log(child.toString()); \u002F\u002F from Object.prototype\n\n\u002F\u002F Constructor functions (old way)\nfunction Animal(type) { this.type = type; }\nAnimal.prototype.speak = function() { console.log(`${this.type} speaks`); };\nconst dog = new Animal('dog');\ndog.speak(); \u002F\u002F 'dog speaks'\nconsole.log(dog.__proto__ === Animal.prototype); \u002F\u002F true\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F ES6 classes (syntactic sugar over prototypes)\nclass Vehicle {\n  constructor(wheels) { this.wheels = wheels; }\n  move() { console.log('Moving'); }\n}\nclass Car extends Vehicle {\n  constructor(brand) {\n    super(4);\n    this.brand = brand;\n  }\n  honk() { console.log('Beep'); }\n}\nconst tesla = new Car('Tesla');\nconsole.log(tesla instanceof Car);      \u002F\u002F true\nconsole.log(tesla instanceof Vehicle);  \u002F\u002F true\nconsole.log(tesla.__proto__ === Car.prototype); \u002F\u002F true\nconsole.log(Car.prototype.__proto__ === Vehicle.prototype); \u002F\u002F true\n\n\u002F\u002F Prototype chain traversal\nfunction getPrototypeChain(obj) {\n  const chain = [];\n  let current = obj;\n  while (current) {\n    chain.push(current.constructor?.name || 'null');\n    current = Object.getPrototypeOf(current);\n  }\n  return chain;\n}\nconsole.log(getPrototypeChain([])); \u002F\u002F ['Array', 'Object', 'null']\n\n\u002F\u002F Property shadowing\nconst parentObj = { color: 'red' };\nconst childObj = Object.create(parentObj);\nchildObj.color = 'blue';\nconsole.log(childObj.color); \u002F\u002F 'blue' (own property shadows parent)\ndelete childObj.color;\nconsole.log(childObj.color); \u002F\u002F 'red' (now from prototype)\n```\n\n**Execution Flow:**\nWhen reading `obj.prop`: JavaScript checks `obj` for own property. If not found, follows `[[Prototype]]` link to prototype object, repeating until found or `null` (returns `undefined`). Setting a property always creates an own property (doesn't modify prototype).\n\n**Practical Usage:**\n- Sharing methods across instances (memory efficiency).\n- Creating object inheritance hierarchies.\n- Polyfilling: adding methods to built-in prototypes (discouraged in production).\n\n**Interview Insight:**\n`Object.create()` sets prototype directly. `new Constructor()` does: `const obj = Object.create(Constructor.prototype); Constructor.call(obj);`. ES6 `class` is syntactic sugar but introduces `super` and better inheritance handling. The prototype chain is live: modifications to prototype affect all inheriting objects.\n\n**Common Mistakes:**\n- Using `for...in` without `hasOwnProperty` (iterates prototype properties).\n- Confusing `prototype` (property on constructor) with `__proto__` (internal link).\n- Overwriting `Constructor.prototype` after instances were created (breaks inheritance).\n\n**Real-world Example:**\nExtending built-in arrays: `class EnhancedArray extends Array { last() { return this[this.length - 1]; } }` – instances inherit from `EnhancedArray.prototype`, which inherits from `Array.prototype`.\n\n**Advanced Notes:**\n`Object.setPrototypeOf()` (slow, avoid). `Object.getPrototypeOf()` standard way. `Reflect` API provides similar. Prototype chain terminates with `Object.prototype` (except `Object.create(null)`). Performance: property lookup along chain has cost; modern engines optimize with inline caching and hidden classes.",[223,224,225,226],"prototypes","inheritance","oop","prototype-chain",{"id":228,"category":35,"question":229,"answer":230,"level":214,"tags":231},28,"What are call, apply, and bind? How do they differ and when would you use each?","**Concept Explanation:**\n`call`, `apply`, and `bind` are methods available on functions to control the `this` context. `call` invokes function with given `this` and arguments passed individually. `apply` is similar but arguments passed as array. `bind` returns a new function with `this` bound permanently (does not invoke immediately).\n\n**Syntax Explanation:**\n```javascript\nfunction greet(greeting, punctuation) {\n  console.log(`${greeting}, ${this.name}${punctuation}`);\n}\n\nconst user = { name: 'Alice' };\n\n\u002F\u002F call: individual arguments\ngreet.call(user, 'Hello', '!'); \u002F\u002F 'Hello, Alice!'\n\n\u002F\u002F apply: array of arguments\ngreet.apply(user, ['Hi', '?']); \u002F\u002F 'Hi, Alice?'\n\n\u002F\u002F bind: returns bound function\nconst boundGreet = greet.bind(user, 'Hey');\nboundGreet('!!'); \u002F\u002F 'Hey, Alice!!'\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Borrowing methods\nconst arrayLike = { 0: 'a', 1: 'b', length: 2 };\nconst realArray = Array.prototype.slice.call(arrayLike);\n\u002F\u002F or Array.from(arrayLike)\n\n\u002F\u002F Finding max in array with apply\nconst numbers = [5, 1, 9, 3];\nconst max = Math.max.apply(null, numbers); \u002F\u002F 9 (spread modern: ...numbers)\n\n\u002F\u002F Event handler binding (pre-React hooks)\nclass Button {\n  constructor(label) { this.label = label; }\n  handleClick() { console.log(`Clicked ${this.label}`); }\n}\nconst btn = new Button('Submit');\n\u002F\u002F setTimeout(btn.handleClick, 1000); \u002F\u002F 'this' lost\nsetTimeout(btn.handleClick.bind(btn), 1000); \u002F\u002F correct\n\n\u002F\u002F Partial application with bind\nfunction multiply(a, b) { return a * b; }\nconst double = multiply.bind(null, 2);\nconsole.log(double(5)); \u002F\u002F 10\nconst triple = multiply.bind(null, 3);\nconsole.log(triple(5)); \u002F\u002F 15\n```\n\n**Practical Usage:**\n- Borrowing array methods on array-likes (NodeList, arguments).\n- Setting `this` for event handlers in classes.\n- Partial application (pre-filling arguments).\n- Function currying.\n\n**Interview Insight:**\n`bind` returns a new function; `call`\u002F`apply` invoke immediately. `bind` is often used with `setTimeout`, event listeners, or React class components. In modern code, arrow functions often replace `bind` by capturing lexical `this`. However, `bind` is still useful for partial application.\n\n**Common Mistakes:**\n- Forgetting that `bind` doesn't invoke the function.\n- Using `call`\u002F`apply` with arrow functions (arrow functions ignore `this` binding).\n- Passing `null` as `this` (reverts to global in non-strict mode).\n\n**Real-world Example:**\nConverting `arguments` object to array: `const args = Array.prototype.slice.call(arguments);` (though rest parameters `...args` are preferred).\n\n**Advanced Notes:**\n`bind` can be polyfilled. Bound functions have internal `[[BoundThis]]` and `[[BoundArguments]]`. Multiple binds: subsequent binds only affect `this` if the function is not already bound (only the first bind matters). `call` and `apply` performance is similar; choose based on argument format.",[232,233,234,175,39],"call","apply","bind",{"id":236,"category":237,"question":238,"answer":239,"level":214,"tags":240},29,"DOM & Events","What is event delegation? How does it work and why is it useful? Provide an example.","**Concept Explanation:**\nEvent delegation is a technique where a single event listener is attached to a parent element to handle events on its child elements, leveraging event bubbling. Instead of attaching listeners to many individual children, you catch events at a higher level and use `event.target` to identify the actual element clicked.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Without delegation (attaching to each button)\ndocument.querySelectorAll('.btn').forEach(btn => {\n  btn.addEventListener('click', () => console.log(btn.textContent));\n});\n\n\u002F\u002F With delegation (single listener on parent)\nconst container = document.getElementById('button-container');\ncontainer.addEventListener('click', (event) => {\n  if (event.target.classList.contains('btn')) {\n    console.log(event.target.textContent);\n  }\n});\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Dynamic elements\nconst parent = document.querySelector('.todo-list');\nparent.addEventListener('click', (e) => {\n  if (e.target.matches('.delete-btn')) {\n    e.target.closest('.todo-item').remove();\n  } else if (e.target.matches('.edit-btn')) {\n    \u002F\u002F handle edit\n  }\n});\n\u002F\u002F New dynamically added todo items work automatically\n\n\u002F\u002F Dropdown menu\nconst menu = document.querySelector('#menu');\nmenu.addEventListener('click', (e) => {\n  if (e.target.tagName === 'A') {\n    e.preventDefault();\n    console.log(`Navigating to ${e.target.href}`);\n  }\n});\n\n\u002F\u002F Handling nested elements\ncontainer.addEventListener('click', (e) => {\n  const button = e.target.closest('.btn'); \u002F\u002F finds nearest button ancestor\n  if (button) {\n    console.log(button.dataset.id);\n  }\n});\n```\n\n**Execution Flow:**\n1. Child element (e.g., button) is clicked.\n2. Event bubbles up from target to parent container.\n3. Parent's listener checks `event.target` or uses `closest()`.\n4. Handler executes based on matched element.\n\n**Practical Usage:**\n- Handling dynamic content (items added after page load).\n- Reducing memory usage (fewer listeners).\n- Simplifying code for lists, tables, menus.\n- Performance improvement when many similar elements exist.\n\n**Interview Insight:**\nEvent delegation relies on event bubbling, which doesn't work for events that don't bubble (focus, blur, scroll, load – use capturing phase). `event.target` is the actual clicked element; `event.currentTarget` is the element with the listener. Use `matches()` or `closest()` for robust element detection.\n\n**Common Mistakes:**\n- Assuming `event.target` is the exact element you want (may be nested).\n- Delegating for events that don't bubble (use capturing or manual dispatch).\n- Stopping propagation (`stopPropagation`) breaks delegation for parent listeners.\n\n**Real-world Example:**\nTodo list app: Instead of adding delete listeners to each new todo item, attach one listener to the `\u003Cul>` parent. When user clicks delete, remove the parent `\u003Cli>`.\n\n**Advanced Notes:**\nEvent delegation can impact performance if the parent receives extremely high-frequency events (mousemove) – filter early. For complex UIs, consider using `requestAnimationFrame` to throttle. Synthetic event systems (React) also implement delegation at root.",[241,81,89,242],"event-delegation","performance",{"id":244,"category":245,"question":246,"answer":247,"level":214,"tags":248},30,"Performance Optimization","Explain debounce and throttle. Provide implementation examples and use cases.","**Concept Explanation:**\nDebounce and throttle are techniques to limit the rate at which a function executes. Debounce delays execution until after a pause (e.g., after user stops typing). Throttle ensures function executes at most once per specified interval (e.g., every 200ms while scrolling).\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Debounce: waits for pause\ndebounce(() => searchAPI(query), 300);\n\n\u002F\u002F Throttle: at most once per interval\nthrottle(() => updateScrollPosition(), 200);\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Debounce implementation\nfunction debounce(fn, delay) {\n  let timerId;\n  return function(...args) {\n    clearTimeout(timerId);\n    timerId = setTimeout(() => fn.apply(this, args), delay);\n  };\n}\n\n\u002F\u002F Throttle implementation (leading edge)\nfunction throttle(fn, limit) {\n  let inThrottle = false;\n  return function(...args) {\n    if (!inThrottle) {\n      fn.apply(this, args);\n      inThrottle = true;\n      setTimeout(() => { inThrottle = false; }, limit);\n    }\n  };\n}\n\n\u002F\u002F Throttle with trailing edge\nfunction throttleTrailing(fn, limit) {\n  let lastCall = 0;\n  return function(...args) {\n    const now = Date.now();\n    if (now - lastCall >= limit) {\n      lastCall = now;\n      fn.apply(this, args);\n    }\n  };\n}\n\n\u002F\u002F Usage examples\nconst searchInput = document.getElementById('search');\nsearchInput.addEventListener('input', debounce((e) => {\n  console.log('Searching for:', e.target.value);\n}, 300));\n\nwindow.addEventListener('scroll', throttle(() => {\n  console.log('Scroll position:', window.scrollY);\n}, 200));\n\n\u002F\u002F Resize event with debounce\nwindow.addEventListener('resize', debounce(() => {\n  console.log('Resize finished');\n}, 250));\n```\n\n**Practical Usage:**\n- **Debounce**: search input suggestions, form validation on typing, resize handler, save draft on pause.\n- **Throttle**: scroll position updates, infinite scroll loading, game input, window resize during drag, rate-limiting API calls.\n\n**Interview Insight:**\nDebounce delays execution; throttle guarantees execution at regular intervals. For search, debounce prevents API call on every keystroke. For scroll, throttle prevents excessive calculations. Implementations can have leading, trailing, or both edges.\n\n**Common Mistakes:**\n- Using debounce when throttle is needed (progress indicators).\n- Forgetting to preserve `this` context in returned function.\n- Not canceling debounce on component unmount (memory leak).\n\n**Real-world Example:**\nChat input sending \"typing\" indicators: throttle every 2 seconds to notify server user is typing. Autosave form: debounce with 1 second delay to save when user pauses.\n\n**Advanced Notes:**\nModern libraries like Lodash provide `_.debounce` and `_.throttle` with options (leading, trailing, maxWait). Cancelable debounce returns a function with `.cancel()`. For animation, `requestAnimationFrame` throttling is better for visual updates.",[249,250,242,251],"debounce","throttle","optimization",{"id":253,"category":254,"question":255,"answer":256,"level":214,"tags":257},31,"Execution Context & Event Loop","Explain the JavaScript execution context. What is the event loop and how do microtasks and macrotasks differ?","**Concept Explanation:**\nExecution context is the environment where JavaScript code is evaluated (global, function, or eval). Each context has a variable environment, scope chain, and `this`. The event loop is the mechanism that coordinates execution: call stack, microtask queue (promises, mutation observers), and macrotask queue (setTimeout, I\u002FO). Microtasks execute before next macrotask.\n\n**Syntax Explanation:**\n```javascript\nconsole.log('1'); \u002F\u002F sync\nsetTimeout(() => console.log('2'), 0); \u002F\u002F macrotask\nPromise.resolve().then(() => console.log('3')); \u002F\u002F microtask\nconsole.log('4'); \u002F\u002F sync\n\u002F\u002F Output: 1,4,3,2\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Event loop order demonstration\nfunction loopExample() {\n  console.log('Start');\n  \n  setTimeout(() => console.log('Timeout'), 0);\n  \n  Promise.resolve()\n    .then(() => console.log('Promise1'))\n    .then(() => console.log('Promise2'));\n  \n  queueMicrotask(() => console.log('Microtask'));\n  \n  console.log('End');\n}\n\u002F\u002F Output: Start, End, Promise1, Microtask, Promise2, Timeout\n\n\u002F\u002F Recursive macrotask vs microtask (blocking)\nfunction recursiveMicrotask(count) {\n  if (count > 0) {\n    Promise.resolve().then(() => recursiveMicrotask(count - 1));\n  }\n}\n\u002F\u002F recursiveMicrotask(10000); \u002F\u002F starves macrotasks, page unresponsive\n\nfunction recursiveMacrotask(count) {\n  if (count > 0) {\n    setTimeout(() => recursiveMacrotask(count - 1), 0);\n  }\n}\n\u002F\u002F Allows UI updates between iterations\n```\n\n**Execution Flow:**\n1. Execute all synchronous code (call stack).\n2. When stack empty, process all microtasks (until queue empty).\n3. Take one macrotask from queue, execute it (may add new microtasks).\n4. Repeat step 2-3.\n\n**Practical Usage:**\n- Using microtasks for async operations that need to run before rendering (promises, `queueMicrotask`).\n- Using macrotasks for deferring work (`setTimeout`, `setInterval`, `postMessage`).\n\n**Interview Insight:**\nEvent loop priority: synchronous > microtasks > macrotasks (one per loop). Rendering occurs between macrotasks. `setTimeout(fn, 0)` doesn't execute immediately; it waits for current microtask queue and any pending macrotasks? Actually: after current microtasks, then next macrotask (which may be the timeout).\n\n**Common Mistakes:**\n- Long-running microtasks block UI (e.g., recursive promises).\n- Assuming `setTimeout(fn, 0)` executes before promise callbacks.\n- Not understanding that `async\u002Fawait` uses promises (microtasks).\n\n**Real-world Example:**\nReact state updates (batched) use microtasks to batch updates before rendering. `useEffect` runs after paint (macrotask or microtask? React schedules after layout\u002Fpaint).\n\n**Advanced Notes:**\nEach event loop iteration has: execute oldest macrotask -> microtasks -> requestAnimationFrame -> rendering -> next macrotask. `queueMicrotask` API standardizes microtask scheduling. Node.js event loop differs (phases: timers, I\u002FO, idle, poll, check, close).",[258,259,260,261],"event-loop","execution-context","microtasks","macrotasks",{"id":263,"category":264,"question":265,"answer":266,"level":214,"tags":267},32,"Memory Management","What are common memory leaks in JavaScript applications? How to detect and fix them?","**Concept Explanation:**\nMemory leaks occur when memory that is no longer needed is not released. Common causes: global variables, forgotten timers\u002Fcallbacks, detached DOM elements, closures retaining large data, and event listeners not removed. Detection via browser DevTools (Memory tab) and performance monitoring.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Leak: accidental global\nfunction leak() {\n  leakedVar = 'This becomes global';\n}\n\n\u002F\u002F Leak: forgotten timer\nlet largeData = new Array(1000000);\nsetInterval(() => {\n  console.log(largeData.length); \u002F\u002F largeData never released\n}, 1000);\n\n\u002F\u002F Fix: clear timer when done\nconst timer = setInterval(...);\nclearInterval(timer);\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F 1. Detached DOM elements\nlet detachedNode = document.createElement('div');\ndocument.body.appendChild(detachedNode);\ndetachedNode.remove();\n\u002F\u002F still referenced in variable, memory leak\ndetachedNode = null; \u002F\u002F fix\n\n\u002F\u002F 2. Event listeners not removed\nclass Component {\n  constructor() {\n    this.handleClick = this.handleClick.bind(this);\n    window.addEventListener('resize', this.handleClick);\n  }\n  destroy() {\n    window.removeEventListener('resize', this.handleClick); \u002F\u002F fix\n  }\n}\n\n\u002F\u002F 3. Closures holding large data\nfunction outer() {\n  const hugeArray = new Array(1000000);\n  return function inner() {\n    console.log('I only need outer variable, not hugeArray');\n    \u002F\u002F inner holds reference to entire outer scope\n  };\n}\n\u002F\u002F Fix: use hugeArray only if needed, or nullify after use\n\n\u002F\u002F 4. Out-of-scope variables in callbacks\nasync function fetchData() {\n  const bigData = await getBigData();\n  setTimeout(() => {\n    console.log(bigData.length); \u002F\u002F retains bigData\n  }, 10000);\n}\n\u002F\u002F Fix: set bigData = null after use if not needed\n```\n\n**Detecting Leaks:**\n- Chrome DevTools: Performance monitor (JS heap size), Memory tab (heap snapshot compare before\u002Fafter operations).\n- `performance.memory` API (Chrome only).\n- Look for steadily increasing heap size without drops.\n\n**Practical Usage:**\n- Always clean up event listeners in `destroy`\u002F`useEffect` cleanup.\n- Avoid global variables (use `'use strict'`, modules).\n- Nullify references to large objects before long-running operations.\n- Use `WeakMap`\u002F`WeakSet` for caches that should not prevent GC.\n\n**Interview Insight:**\nModern garbage collectors (mark-and-sweep) handle most leaks, but references from roots (global, active timers, live DOM) prevent collection. Detached DOM trees are common: elements removed from DOM but still referenced in JS. Use `FinalizationRegistry` for advanced cleanup but not for critical logic.\n\n**Common Mistakes:**\n- Adding event listeners in SPA without removing (accumulates).\n- Storing DOM references in closures unnecessarily.\n- Using large caches without size limits.\n\n**Real-world Example:**\nReact component with `setInterval` but no cleanup: `useEffect(() => { const id = setInterval(() => {}, 1000); return () => clearInterval(id); }, [])`.\n\n**Advanced Notes:**\n`FinalizationRegistry` allows callbacks when objects are garbage collected (use with caution). `WeakRef` holds weak reference (doesn't prevent GC). Chrome DevTools can take heap snapshots and compare allocations. Detach iframe? Yes, iframes can cause leaks if not removed properly.",[268,269,242,270],"memory-leaks","memory-management","garbage-collection",{"id":272,"category":273,"question":274,"answer":275,"level":214,"tags":276},33,"Objects & Data Structures","What is the difference between deep copy and shallow copy? How to implement each in JavaScript?","**Concept Explanation:**\nShallow copy creates a new object that copies the top-level properties; nested objects are still referenced (shared). Deep copy creates a completely independent copy, recursively copying all nested objects. Primitive values are always copied by value (not reference).\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Shallow copy methods\nconst original = { a: 1, b: { c: 2 } };\nconst spreadCopy = { ...original };\nconst objectAssign = Object.assign({}, original);\nconst arrayShallow = [...originalArray];\n\noriginal.b.c = 99;\nconsole.log(spreadCopy.b.c); \u002F\u002F 99 (shared reference)\n\n\u002F\u002F Deep copy methods\nconst jsonCopy = JSON.parse(JSON.stringify(original)); \u002F\u002F limited\nconst structuredCloneCopy = structuredClone(original); \u002F\u002F modern\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Shallow copy pitfalls\nconst arr = [{ x: 1 }, { y: 2 }];\nconst shallow = arr.slice();\nshallow[0].x = 99;\nconsole.log(arr[0].x); \u002F\u002F 99 (shared)\n\n\u002F\u002F Deep copy with structuredClone (ES2021)\nconst deep = structuredClone(original);\noriginal.b.c = 100;\nconsole.log(deep.b.c); \u002F\u002F 2 (independent)\n\n\u002F\u002F Custom deep clone (recursive)\nfunction deepClone(obj, hash = new WeakMap()) {\n  if (obj === null || typeof obj !== 'object') return obj;\n  if (hash.has(obj)) return hash.get(obj); \u002F\u002F handle circular\n  \n  const clone = Array.isArray(obj) ? [] : {};\n  hash.set(obj, clone);\n  \n  for (let key in obj) {\n    if (obj.hasOwnProperty(key)) {\n      clone[key] = deepClone(obj[key], hash);\n    }\n  }\n  return clone;\n}\n\n\u002F\u002F Handling special types (Date, RegExp, Map, Set)\nfunction deepCloneAdvanced(obj) {\n  if (obj instanceof Date) return new Date(obj);\n  if (obj instanceof RegExp) return new RegExp(obj);\n  if (obj instanceof Map) return new Map([...obj].map(([k,v]) => [deepCloneAdvanced(k), deepCloneAdvanced(v)]));\n  if (obj instanceof Set) return new Set([...obj].map(v => deepCloneAdvanced(v)));\n  \u002F\u002F ... continue with generic object\u002Farray\n}\n```\n\n**Practical Usage:**\n- Shallow copy: updating React state immutably (spread for top-level).\n- Deep copy: storing application state snapshots, duplicating complex objects.\n- `structuredClone` is recommended for most deep copy needs.\n\n**Interview Insight:**\n`JSON.parse(JSON.stringify())` fails with `undefined`, functions, symbols, Dates (become strings), RegExp (becomes empty object), circular references (throws). `structuredClone` handles Dates, RegExp, Maps, Sets, Blobs, circular references, but not functions or DOM nodes. Manual deep clone can be expensive for large objects.\n\n**Common Mistakes:**\n- Using shallow copy expecting full independence.\n- Using JSON method for objects with functions or undefined (silent data loss).\n- Deep copying large objects frequently (performance hit).\n\n**Real-world Example:**\nRedux reducer: `return { ...state, user: { ...state.user, name: action.payload } }` (shallow). For time-travel debugging, you might deep clone state.\n\n**Advanced Notes:**\n`Object.freeze()` can enforce immutability. Libraries like Lodash `_.cloneDeep`. `structuredClone` is supported in all modern browsers and Node.js 17+. `MessageChannel` can also deep clone. Performance: shallow copy is O(n), deep copy O(n * depth).",[277,278,279,73],"deep-copy","shallow-copy","immutability",{"id":281,"category":118,"question":282,"answer":283,"level":214,"tags":284},34,"Compare ES modules (import\u002Fexport) with CommonJS (require\u002Fmodule.exports). What are the key differences in loading, syntax, and usage?","**Concept Explanation:**\nES modules (ESM) are the official JavaScript module system, asynchronous, and statically analyzable. CommonJS is the Node.js module system, synchronous, and dynamic. ESM uses `import`\u002F`export`; CommonJS uses `require()` and `module.exports`. ESM is newer, recommended for browser and modern Node.js.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F CommonJS (Node.js)\n\u002F\u002F math.cjs\nconst add = (a, b) => a + b;\nconst subtract = (a, b) => a - b;\nmodule.exports = { add, subtract };\n\n\u002F\u002F main.cjs\nconst { add } = require('.\u002Fmath.cjs');\nconsole.log(add(2,3));\n\n\u002F\u002F ES Modules (browser or Node with type:module)\n\u002F\u002F math.js\nexport const add = (a, b) => a + b;\nexport const subtract = (a, b) => a - b;\n\n\u002F\u002F main.js\nimport { add } from '.\u002Fmath.js';\nconsole.log(add(2,3));\n\n\u002F\u002F Default export\n\u002F\u002F logger.js\nexport default function log(msg) { console.log(msg); }\n\u002F\u002F main.js\nimport log from '.\u002Flogger.js';\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F ESM: static imports are hoisted\nimport { something } from '.\u002Fmodule.js'; \u002F\u002F runs before module code\n\n\u002F\u002F ESM: dynamic import (async)\nconst module = await import('.\u002Fdynamic.js');\n\n\u002F\u002F CommonJS: require can be called conditionally\nif (condition) {\n  const module = require('.\u002Fconditional.js');\n}\n\n\u002F\u002F ESM: live bindings (values update)\n\u002F\u002F counter.js\nexport let count = 0;\nexport function increment() { count++; }\n\u002F\u002F main.js\nimport { count, increment } from '.\u002Fcounter.js';\nconsole.log(count); \u002F\u002F 0\nincrement();\nconsole.log(count); \u002F\u002F 1 (live binding)\n\n\u002F\u002F CommonJS: copies values\n\u002F\u002F counter.cjs\nlet count = 0;\nfunction increment() { count++; }\nmodule.exports = { count, increment };\n\u002F\u002F main.cjs\nconst { count, increment } = require('.\u002Fcounter.cjs');\nconsole.log(count); \u002F\u002F 0\nincrement();\nconsole.log(count); \u002F\u002F 0 (not updated)\n```\n\n**Execution Flow:**\n- CommonJS: loads modules synchronously at runtime (blocking).\n- ESM: loads asynchronously, parses imports first, creates module graph, then evaluates.\n\n**Practical Usage:**\n- Node.js: prefer ESM for new projects (`\"type\": \"module\"` in package.json). Use `.cjs` extension for CommonJS.\n- Browsers: only support ESM (`\u003Cscript type=\"module\">`).\n- Build tools: both work, but tree shaking works with ESM static structure.\n\n**Interview Insight:**\nESM supports top-level `await` (only in modules). ESM is strict mode by default. `import.meta` provides module metadata. CommonJS `require` can be called from ESM using `import { createRequire } from 'module'`. Circular dependencies: CommonJS returns incomplete exports; ESM handles better via live bindings.\n\n**Common Mistakes:**\n- Trying to use `import` without `type=\"module\"` in browser.\n- Mixing `.mjs` and `.cjs` incorrectly.\n- Assuming ESM `require` equivalent (not available).\n\n**Real-world Example:**\nExpress app: CommonJS historically used, but Node.js now supports ESM: `import express from 'express';` with `\"type\": \"module\"`.\n\n**Advanced Notes:**\nESM has `import.meta.resolve()` for resolution. Module loaders: Node.js uses algorithm based on file extension and package exports. Bundle tools (Webpack, Vite) use ESM for better tree shaking. `require.resolve()` for path resolution in CommonJS.",[122,285,286,287],"esm","commonjs","nodejs",{"id":289,"category":273,"question":290,"answer":291,"level":214,"tags":292},35,"What are WeakMap and WeakSet? How do they differ from Map and Set, and when should you use them?","**Concept Explanation:**\n`WeakMap` and `WeakSet` hold \"weak\" references to their keys (objects only). They do not prevent garbage collection of those objects. Keys in `WeakMap` must be objects; values can be any type. `WeakSet` values must be objects. They are not iterable and have no `size` property, enabling memory-safe metadata storage.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Map vs WeakMap\nconst map = new Map();\nlet obj = { data: 'important' };\nmap.set(obj, 'metadata');\nobj = null; \u002F\u002F object still in Map (memory leak)\n\u002F\u002F map still holds reference\n\nconst weakMap = new WeakMap();\nlet obj2 = { data: 'important' };\nweakMap.set(obj2, 'metadata');\nobj2 = null; \u002F\u002F object can be garbage collected\n\u002F\u002F weakMap entry automatically removed\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F WeakMap usage: private data for objects\nconst privateData = new WeakMap();\nclass Person {\n  constructor(name) {\n    privateData.set(this, { name });\n  }\n  getName() {\n    return privateData.get(this).name;\n  }\n}\nconst alice = new Person('Alice');\nconsole.log(alice.getName()); \u002F\u002F 'Alice'\n\u002F\u002F No way to access private data except through methods\n\n\u002F\u002F WeakSet for unique object tracking without preventing GC\nconst visitedNodes = new WeakSet();\nfunction traverse(node) {\n  if (visitedNodes.has(node)) return;\n  visitedNodes.add(node);\n  \u002F\u002F process node\n  node.children.forEach(child => traverse(child));\n}\n\u002F\u002F As tree nodes are removed from DOM, WeakSet doesn't retain them\n\n\u002F\u002F Difference: Map can iterate, WeakMap cannot\nconst mapExample = new Map();\nmapExample.set('key', 'value');\nfor (const [k,v] of mapExample) {} \u002F\u002F works\n\nconst weakMapExample = new WeakMap();\n\u002F\u002F weakMapExample.keys() \u002F\u002F Error, not iterable\n```\n\n**Practical Usage:**\n- **WeakMap**: storing private data, caching DOM element metadata (e.g., event handlers, component instances).\n- **WeakSet**: tracking object visitation, marking objects without preventing GC.\n- Avoid memory leaks when objects are no longer needed.\n\n**Interview Insight:**\nWeak references allow garbage collector to collect the referenced object if no other strong references exist. This makes WeakMap\u002FWeakSet ideal for associating data with objects that you don't control the lifecycle of (e.g., DOM nodes). They are not iterable because the set of keys can change at any time due to GC.\n\n**Common Mistakes:**\n- Trying to iterate or get size of WeakMap\u002FWeakSet (not possible).\n- Using primitive values as keys (TypeError).\n- Assuming weak references are immediate (GC runs non-deterministically).\n\n**Real-world Example:**\nIn a UI library, you might cache event handlers per DOM node: `const handlers = new WeakMap(); handlers.set(button, onClickHandler);` When button is removed from DOM and no other references, both button and handler are eligible for GC.\n\n**Advanced Notes:**\n`FinalizationRegistry` can be used with WeakRef for cleanup callbacks. WeakMap\u002FWeakSet are not enumerable, which is intentional. Use `WeakRef` directly for weak references to objects. In Node.js, `WeakMap` is available. The garbage collector may reclaim objects even if they are still in WeakMap; you cannot rely on entry existence.",[293,294,216,270],"weakmap","weakset",{"id":296,"category":93,"question":297,"answer":298,"level":214,"tags":299},36,"What are Symbols in JavaScript? How are they used as unique property keys and well-known symbols?","**Concept Explanation:**\n`Symbol` is a primitive type introduced in ES6, guaranteeing uniqueness. Each symbol value is immutable and unique, even if created with the same description. Symbols are often used as object property keys to avoid name collisions and to define non-enumerable properties. Well-known symbols customize language behavior (e.g., `Symbol.iterator`).\n\n**Syntax Explanation:**\n```javascript\nconst sym1 = Symbol();\nconst sym2 = Symbol('description');\nconst sym3 = Symbol('description');\nconsole.log(sym2 === sym3); \u002F\u002F false (unique)\n\n\u002F\u002F Symbol as property key\nconst id = Symbol('id');\nconst user = {\n  name: 'Alice',\n  [id]: 12345\n};\nconsole.log(user[id]); \u002F\u002F 12345\nconsole.log(Object.keys(user)); \u002F\u002F ['name'] (symbols not enumerated)\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Well-known symbols\n\u002F\u002F 1. Symbol.iterator (making objects iterable)\nconst range = {\n  from: 1,\n  to: 5,\n  [Symbol.iterator]() {\n    this.current = this.from;\n    return {\n      next: () => {\n        if (this.current \u003C= this.to) {\n          return { value: this.current++, done: false };\n        }\n        return { done: true };\n      }\n    };\n  }\n};\nfor (const num of range) console.log(num); \u002F\u002F 1,2,3,4,5\n\n\u002F\u002F 2. Symbol.toStringTag\nclass MyClass {\n  get [Symbol.toStringTag]() { return 'MyCustomClass'; }\n}\nconsole.log(Object.prototype.toString.call(new MyClass())); \u002F\u002F '[object MyCustomClass]'\n\n\u002F\u002F 3. Symbol.toPrimitive (custom type conversion)\nconst specialNumber = {\n  [Symbol.toPrimitive](hint) {\n    if (hint === 'number') return 42;\n    if (hint === 'string') return 'forty-two';\n    return null;\n  }\n};\nconsole.log(+specialNumber); \u002F\u002F 42\nconsole.log(`${specialNumber}`); \u002F\u002F 'forty-two'\n\n\u002F\u002F Global symbol registry\nconst globalSym = Symbol.for('app.uniqueId');\nconst sameGlobalSym = Symbol.for('app.uniqueId');\nconsole.log(globalSym === sameGlobalSym); \u002F\u002F true\nconsole.log(Symbol.keyFor(globalSym)); \u002F\u002F 'app.uniqueId'\n```\n\n**Practical Usage:**\n- Preventing property name collisions in libraries or mixins.\n- Creating private-like properties (not truly private but non-enumerable).\n- Implementing iteration protocols, custom string tagging, or coercion.\n\n**Interview Insight:**\nSymbol properties are skipped in `for...in`, `Object.keys()`, but accessible via `Object.getOwnPropertySymbols()`. `Reflect.ownKeys()` returns both string and symbol keys. Well-known symbols allow hooking into JavaScript internals (e.g., `Symbol.hasInstance`, `Symbol.match`).\n\n**Common Mistakes:**\n- Assuming `Symbol('desc')` === `Symbol('desc')` (false).\n- Thinking symbols are private (they are not; they can be accessed via reflection).\n- Using `new Symbol()` (TypeError, Symbol is not a constructor).\n\n**Real-world Example:**\nRedux: using symbols for action types to avoid collisions. Libraries use `Symbol` for internal methods to avoid overwriting user properties.\n\n**Advanced Notes:**\n`Symbol.asyncIterator` for async iteration. `Symbol.dispose` (proposal) for resource management. `Symbol.metadata` for decorators. Symbols are not automatically converted to strings; use `String(sym)` or `sym.toString()`. `Symbol.prototype.description` returns description string.",[300,23,301,302],"symbols","unique-keys","well-known-symbols",{"id":304,"category":93,"question":305,"answer":306,"level":214,"tags":307},37,"What are iterators and generators in JavaScript? Provide examples and explain their relationship with the iteration protocol.","**Concept Explanation:**\nIterators are objects that implement the iterator protocol: a `next()` method returning `{ value, done }`. Generators are functions (`function*`) that produce iterators, can yield multiple values, and can pause\u002Fresume execution. The iteration protocol allows any object to become iterable by implementing `[Symbol.iterator]`.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Manual iterator\nfunction createCounter(max) {\n  let count = 0;\n  return {\n    next() {\n      if (count \u003C max) return { value: ++count, done: false };\n      return { value: undefined, done: true };\n    }\n  };\n}\nconst counter = createCounter(3);\nconsole.log(counter.next()); \u002F\u002F { value:1, done:false }\n\n\u002F\u002F Generator function\nfunction* counterGen(max) {\n  for (let i = 1; i \u003C= max; i++) {\n    yield i;\n  }\n}\nconst gen = counterGen(3);\nconsole.log(gen.next()); \u002F\u002F { value:1, done:false }\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Making custom object iterable\nconst team = {\n  members: ['Alice', 'Bob', 'Charlie'],\n  [Symbol.iterator]: function* () {\n    for (const member of this.members) {\n      yield member;\n    }\n  }\n};\nfor (const person of team) console.log(person); \u002F\u002F Alice, Bob, Charlie\n\n\u002F\u002F Infinite sequence generator\nfunction* fibonacci() {\n  let a = 0, b = 1;\n  while (true) {\n    yield a;\n    [a, b] = [b, a + b];\n  }\n}\nconst fib = fibonacci();\nconsole.log(fib.next().value); \u002F\u002F 0\nconsole.log(fib.next().value); \u002F\u002F 1\nconsole.log(fib.next().value); \u002F\u002F 1\nconsole.log(fib.next().value); \u002F\u002F 2\n\n\u002F\u002F Generator delegation (yield*)\nfunction* generateNumbers() {\n  yield 1;\n  yield* [2, 3]; \u002F\u002F delegates to array iterator\n  yield 4;\n}\nconsole.log([...generateNumbers()]); \u002F\u002F [1,2,3,4]\n\n\u002F\u002F Passing values into generator\nfunction* interactive() {\n  const name = yield 'What is your name?';\n  const age = yield `Hello ${name}, how old are you?`;\n  return `${name} is ${age} years old.`;\n}\nconst it = interactive();\nconsole.log(it.next().value); \u002F\u002F 'What is your name?'\nconsole.log(it.next('Alice').value); \u002F\u002F 'Hello Alice, how old are you?'\nconsole.log(it.next(30).value); \u002F\u002F 'Alice is 30 years old.'\n```\n\n**Practical Usage:**\n- Lazy evaluation (generators produce values on demand).\n- Custom iterable data structures (trees, linked lists).\n- Handling infinite sequences or large datasets without memory overhead.\n- Asynchronous generators (`async function*`) for streaming data.\n\n**Interview Insight:**\nGenerator functions can pause at `yield` and resume later; they maintain state. Use `return()` or `throw()` on generator objects. Spread operator (`...`) and `for...of` consume iterators. Generators are not constructors (cannot use `new`).\n\n**Common Mistakes:**\n- Forgetting that generator returns iterator, not values directly.\n- Using `return` in generator (ends generator).\n- Assuming generator functions are arrow functions (arrow functions cannot be generators).\n\n**Real-world Example:**\nRedux Saga uses generators for side effects: `function* fetchUser() { yield call(api.fetchUser); yield put({ type: 'USER_FETCHED' }); }`.\n\n**Advanced Notes:**\nAsync generators combine `async` and `function*`: `async function* streamData() { while(true) { await delay(1000); yield Date.now(); } }`. Iterators can be consumed via `Array.from()`, `for...of`, spread. The iteration protocol is fundamental to many JavaScript features (maps, sets, arrays, strings).",[308,309,310,23],"iterators","generators","iteration-protocol",{"id":312,"category":93,"question":313,"answer":314,"level":214,"tags":315},38,"How does AbortController work? Demonstrate canceling fetch requests and other async operations.","**Concept Explanation:**\n`AbortController` provides a mechanism to cancel asynchronous operations (like fetch requests). It has a `signal` property passed to the operation and an `abort()` method to trigger cancellation. When aborted, the associated promise rejects with `AbortError`. Can also be used with timers, event listeners, and any custom async operation.\n\n**Syntax Explanation:**\n```javascript\nconst controller = new AbortController();\nconst { signal } = controller;\n\n\u002F\u002F Pass signal to fetch\nfetch('https:\u002F\u002Fapi.example.com\u002Fdata', { signal })\n  .then(res => res.json())\n  .catch(err => {\n    if (err.name === 'AbortError') {\n      console.log('Fetch aborted');\n    }\n  });\n\n\u002F\u002F Abort after timeout\nsetTimeout(() => controller.abort(), 1000);\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Abort multiple fetches with same signal\nconst controller = new AbortController();\nconst signal = controller.signal;\n\nPromise.all([\n  fetch('\u002Fapi\u002Fuser', { signal }),\n  fetch('\u002Fapi\u002Fposts', { signal })\n]).catch(err => {\n  if (err.name === 'AbortError') {\n    console.log('All fetches aborted');\n  }\n});\n\ncontroller.abort(); \u002F\u002F cancels all\n\n\u002F\u002F Abort timeout with controller\nfunction abortableTimeout(ms, signal) {\n  return new Promise((resolve, reject) => {\n    const timer = setTimeout(resolve, ms);\n    signal?.addEventListener('abort', () => {\n      clearTimeout(timer);\n      reject(new DOMException('Timeout aborted', 'AbortError'));\n    });\n  });\n}\n\n\u002F\u002F Race between timeout and fetch\nconst fetchController = new AbortController();\nconst timeoutPromise = abortableTimeout(5000, fetchController.signal);\nconst fetchPromise = fetch('\u002Fapi\u002Fslow', { signal: fetchController.signal });\n\ntry {\n  const result = await Promise.race([fetchPromise, timeoutPromise]);\n  \u002F\u002F if fetch wins, cancel timeout? signal already aborted? Not needed\n} catch (error) {\n  if (error.name === 'AbortError') console.log('Request timed out');\n}\n\u002F\u002F Or manually abort if timeout wins:\ntimeoutPromise.catch(() => fetchController.abort());\n\n\u002F\u002F React useEffect cleanup\nuseEffect(() => {\n  const controller = new AbortController();\n  fetch('\u002Fapi\u002Fdata', { signal: controller.signal })\n    .then(res => res.json())\n    .then(setData)\n    .catch(err => {\n      if (err.name !== 'AbortError') console.error(err);\n    });\n  return () => controller.abort(); \u002F\u002F cleanup on unmount\n}, []);\n```\n\n**Practical Usage:**\n- Cancel in-progress fetch when user navigates away.\n- Implement request timeouts.\n- Stop expensive computations or event listeners.\n- Clean up async operations in React `useEffect`.\n\n**Interview Insight:**\nAbortController is not limited to fetch; any async operation can integrate by checking `signal.aborted` or listening to `abort` event. `AbortSignal.timeout(ms)` is a static method for timeout-only signals (newer browsers). Fetch aborts will also cancel the underlying network request (release resources).\n\n**Common Mistakes:**\n- Forgetting to check `signal.aborted` in custom async functions.\n- Assuming `controller.abort()` rejects immediately (it triggers event, promise rejection happens when operation checks signal).\n- Reusing same controller after abort (create new for each operation).\n\n**Real-world Example:**\nSearch autocomplete: abort previous fetch when user types new query to avoid race conditions.\n```javascript\nlet currentController = null;\nasync function search(query) {\n  if (currentController) currentController.abort();\n  currentController = new AbortController();\n  try {\n    const res = await fetch(`\u002Fsearch?q=${query}`, { signal: currentController.signal });\n    const data = await res.json();\n    displayResults(data);\n  } catch (e) {\n    if (e.name !== 'AbortError') console.error(e);\n  }\n}\n```\n\n**Advanced Notes:**\n`AbortSignal` also has `aborted` property and `throwIfAborted()` method. Multiple signals can be combined via `AbortSignal.any()`. Node.js supports AbortController for file system operations, http requests, etc. The `AbortError` is a `DOMException` (name 'AbortError').",[316,113,317,98],"abortcontroller","cancellation",{"id":319,"category":245,"question":320,"answer":321,"level":214,"tags":322},39,"What are common JavaScript performance optimization techniques? Explain reflow, repaint, and how to minimize layout thrashing.","**Concept Explanation:**\nRepaint: updating element appearance (color, visibility) without changing layout. Reflow: recalculating element positions and geometry (more expensive). Layout thrashing: repeatedly forcing synchronous layout reads\u002Fwrites, causing multiple reflows. Performance optimizations include batching DOM updates, using `requestAnimationFrame`, avoiding forced synchronous layouts, and using CSS transforms\u002Fopacity for animations.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Bad: layout thrashing\nconst divs = document.querySelectorAll('.item');\ndivs.forEach(div => {\n  div.style.width = div.offsetWidth + 10 + 'px'; \u002F\u002F read, then write\n});\n\n\u002F\u002F Good: batch reads then writes\nconst widths = [];\ndivs.forEach(div => widths.push(div.offsetWidth)); \u002F\u002F read phase\ndivs.forEach((div, i) => div.style.width = widths[i] + 10 + 'px'); \u002F\u002F write phase\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Use requestAnimationFrame for animations\nfunction animate() {\n  \u002F\u002F update style\n  element.style.transform = `translateX(${x}px)`;\n  x += 1;\n  if (x \u003C 100) requestAnimationFrame(animate);\n}\nrequestAnimationFrame(animate);\n\n\u002F\u002F DocumentFragment for batch DOM insertions\nconst fragment = document.createDocumentFragment();\nfor (let i = 0; i \u003C 1000; i++) {\n  const li = document.createElement('li');\n  li.textContent = `Item ${i}`;\n  fragment.appendChild(li);\n}\nlist.appendChild(fragment); \u002F\u002F single reflow\n\n\u002F\u002F CSS classes instead of inline style changes\n\u002F\u002F Bad: element.style.width = '100px'; element.style.height = '100px';\n\u002F\u002F Good: element.classList.add('expanded');\n\n\u002F\u002F Virtual DOM (React) batches updates\n\u002F\u002F Debouncing resize handlers\nlet resizeTimer;\nwindow.addEventListener('resize', () => {\n  clearTimeout(resizeTimer);\n  resizeTimer = setTimeout(() => {\n    \u002F\u002F handle resize once after pause\n  }, 150);\n});\n```\n\n**Practical Usage:**\n- Batch DOM reads before writes.\n- Use `transform` and `opacity` for animations (GPU-accelerated).\n- Avoid `offsetHeight`, `getComputedStyle` in tight loops.\n- Use `will-change` for elements that will animate.\n- Lazy load offscreen images.\n\n**Interview Insight:**\nReflow is triggered by geometry changes (width, height, margin, padding) or DOM manipulation. Repaint is triggered by color, background, visibility. Each reflow can affect children and ancestors. Use `display: none` to make temporary changes without reflow (since element is hidden, changes don't cause reflow until shown).\n\n**Common Mistakes:**\n- Reading layout properties inside animation loops (forces reflow each frame).\n- Changing many inline styles individually.\n- Not using `requestAnimationFrame` for visual updates.\n- Adding many DOM elements one by one without fragment.\n\n**Real-world Example:**\nInfinite scroll: throttle scroll handler, read `scrollTop` and `offsetHeight` efficiently, batch load more items using `DocumentFragment`.\n\n**Advanced Notes:**\nThe CSSOM (CSS Object Model) and DOM are separate; layout combines them. `contain` CSS property isolates reflow. `content-visibility` can skip rendering off-screen content. Chrome DevTools Performance tab can identify layout thrashing (shows red bars for forced reflow). Web Workers for heavy computation avoid blocking main thread.",[242,323,324,251,325],"reflow","repaint","layout",{"id":327,"category":109,"question":328,"answer":329,"level":214,"tags":330},40,"How does the MutationObserver API work? Compare it with deprecated DOM events and provide a use case.","**Concept Explanation:**\n`MutationObserver` provides a way to watch for changes in the DOM tree (attributes, child nodes, subtree modifications) without performance penalties of deprecated Mutation Events. It delivers changes in batches asynchronously using a callback, making it suitable for observing dynamically generated content, implementing rich text editors, or reacting to DOM changes from third-party scripts.\n\n**Syntax Explanation:**\n```javascript\nconst observer = new MutationObserver((mutationsList) => {\n  for (const mutation of mutationsList) {\n    if (mutation.type === 'childList') {\n      console.log('Added\u002Fremoved nodes:', mutation.addedNodes, mutation.removedNodes);\n    } else if (mutation.type === 'attributes') {\n      console.log(`Attribute ${mutation.attributeName} changed`);\n    }\n  }\n});\n\nobserver.observe(targetNode, {\n  attributes: true,\n  childList: true,\n  subtree: true,\n  attributeOldValue: true\n});\n\n\u002F\u002F Disconnect when done\nobserver.disconnect();\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Detect when element is added to DOM\nconst container = document.getElementById('dynamic-content');\nconst observer = new MutationObserver((mutations) => {\n  mutations.forEach(mutation => {\n    mutation.addedNodes.forEach(node => {\n      if (node.nodeType === 1 && node.matches('.lazy-image')) {\n        loadImage(node);\n      }\n    });\n  });\n});\nobserver.observe(container, { childList: true, subtree: true });\n\n\u002F\u002F Watching attribute changes (e.g., for data binding)\nconst configEl = document.getElementById('config-panel');\nconst attrObserver = new MutationObserver((mutations) => {\n  mutations.forEach(m => {\n    if (m.attributeName === 'data-theme') {\n      updateTheme(m.target.getAttribute('data-theme'));\n    }\n  });\n});\nattrObserver.observe(configEl, { attributes: true });\n\n\u002F\u002F Character data changes (text content)\nconst textObserver = new MutationObserver((mutations) => {\n  console.log('Text changed:', mutations[0].target.data);\n});\nconst textNode = document.createTextNode('Initial');\ntextObserver.observe(textNode, { characterData: true });\n```\n\n**Practical Usage:**\n- Lazy loading images inserted dynamically.\n- Auto-saving form changes.\n- Implementing undo\u002Fredo in rich text editors.\n- Responding to DOM changes from browser extensions.\n- Detecting when a target element becomes visible for animation.\n\n**Interview Insight:**\nDeprecated Mutation Events (`DOMNodeInserted`, etc.) were synchronous and fired for every change, causing severe performance issues. `MutationObserver` batches changes and is asynchronous (microtask). It can observe attributes, childList, characterData, and subtree. `takeRecords()` empties the queue.\n\n**Common Mistakes:**\n- Forgetting to disconnect observer to prevent memory leaks.\n- Making synchronous DOM changes inside observer callback that cause re-entrant observations (avoid infinite loops).\n- Observing too broad a subtree causing performance overhead.\n\n**Real-world Example:**\nCMS with live preview: observer watches content editable area and syncs changes to preview frame.\n\n**Advanced Notes:**\n`MutationObserver` also observes `data-*` attribute changes. Use `attributeFilter` option to limit observed attributes. For performance, specify `subtree: false` when not needed. `characterDataOldValue` can be used to get previous text. Observers do not observe changes in `ShadowRoot` by default unless configured.",[331,81,242,158],"mutationobserver",{"id":333,"category":109,"question":334,"answer":335,"level":214,"tags":336},41,"What is IntersectionObserver? How does it improve scroll performance compared to scroll event listeners?","**Concept Explanation:**\n`IntersectionObserver` asynchronously observes changes in the intersection of a target element with an ancestor element or the viewport. It eliminates the need for scroll event listeners that cause layout thrashing and use expensive `getBoundingClientRect()` calls. Ideal for lazy loading images, infinite scroll, and triggering animations when elements enter viewport.\n\n**Syntax Explanation:**\n```javascript\nconst observer = new IntersectionObserver((entries) => {\n  entries.forEach(entry => {\n    if (entry.isIntersecting) {\n      console.log('Element entered viewport');\n      \u002F\u002F Load image, start animation, etc.\n      observer.unobserve(entry.target); \u002F\u002F stop observing if needed\n    }\n  });\n}, { threshold: 0.5 }); \u002F\u002F 50% visible\n\nobserver.observe(document.querySelector('.lazy-image'));\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Lazy loading images\nconst imageObserver = new IntersectionObserver((entries, obs) => {\n  entries.forEach(entry => {\n    if (entry.isIntersecting) {\n      const img = entry.target;\n      img.src = img.dataset.src;\n      img.classList.add('loaded');\n      obs.unobserve(img);\n    }\n  });\n});\ndocument.querySelectorAll('[data-src]').forEach(img => imageObserver.observe(img));\n\n\u002F\u002F Infinite scroll (loading more content)\nconst sentinel = document.querySelector('#load-more-sentinel');\nconst infiniteObserver = new IntersectionObserver((entries) => {\n  if (entries[0].isIntersecting) {\n    loadMoreItems();\n  }\n});\ninfiniteObserver.observe(sentinel);\n\n\u002F\u002F Trigger animation when element enters viewport\nconst animateObserver = new IntersectionObserver((entries) => {\n  entries.forEach(entry => {\n    if (entry.isIntersecting) {\n      entry.target.classList.add('fade-in');\n      animateObserver.unobserve(entry.target);\n    }\n  });\n}, { threshold: 0.2, rootMargin: '0px 0px -100px 0px' });\n\n\u002F\u002F Tracking visibility percentage\nconst visibilityObserver = new IntersectionObserver((entries) => {\n  entries.forEach(entry => {\n    const ratio = entry.intersectionRatio;\n    console.log(`Visibility: ${ratio * 100}%`);\n  });\n}, { threshold: [0, 0.25, 0.5, 0.75, 1] });\n```\n\n**Practical Usage:**\n- Lazy loading images, iframes, or videos.\n- Infinite scroll pagination.\n- Analytics tracking (when user sees an element).\n- Implementing sticky elements or headers.\n- Prefetching resources when near viewport.\n\n**Interview Insight:**\n`IntersectionObserver` runs off the main thread and does not block painting. It fires asynchronously (macrotask? Actually microtask? Usually after paint, but better than scroll events which fire on each scroll frame). `rootMargin` allows expanding\u002Fshrinking the root's bounding box. `threshold` can be an array for multiple visibility ratios.\n\n**Common Mistakes:**\n- Not unobserving elements after they load (wastes resources).\n- Setting `threshold` too low causing many callbacks.\n- Using `IntersectionObserver` for tiny elements or animations (use CSS scroll snap instead).\n\n**Real-world Example:**\nE-commerce product listing: lazy load product images as they scroll into view, reducing initial page weight and improving load time.\n\n**Advanced Notes:**\n`IntersectionObserver` also works for observing iframes and shadow DOM. `Polyfill` available for older browsers. `root` can be any scrollable element, not just viewport. Use `observe`, `unobserve`, and `disconnect` methods. Browser support is excellent (except IE). For high-frequency intersection changes, consider using `requestIdleCallback` to handle callbacks.",[337,242,338,339],"intersectionobserver","lazy-loading","scroll",{"id":341,"category":342,"question":343,"answer":344,"level":214,"tags":345},42,"Node.js","What is the Node.js event loop? Explain its phases and how it differs from the browser event loop.","**Concept Explanation:**\nNode.js event loop is a C++ library (libuv) that implements asynchronous I\u002FO. It has distinct phases: timers, pending callbacks, idle\u002Fprepare, poll, check, close callbacks. Unlike browsers, Node.js event loop handles I\u002FO operations and timers in a specific order without rendering steps. Each phase has its own queue.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Node.js event loop phases in order\nsetTimeout(() => console.log('timers'), 0);\nsetImmediate(() => console.log('check'));\nPromise.resolve().then(() => console.log('microtask'));\nprocess.nextTick(() => console.log('nextTick'));\n\u002F\u002F Output order: nextTick, microtask, timers, check\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Demonstrating phase order\nconst fs = require('fs');\n\nfs.readFile(__filename, () => {\n  console.log('I\u002FO callback (poll phase)');\n  setTimeout(() => console.log('timer in I\u002FO'), 0);\n  setImmediate(() => console.log('immediate in I\u002FO'));\n  process.nextTick(() => console.log('nextTick in I\u002FO'));\n});\n\n\u002F\u002F Output order: \n\u002F\u002F I\u002FO callback\n\u002F\u002F nextTick in I\u002FO\n\u002F\u002F immediate in I\u002FO\n\u002F\u002F timer in I\u002FO\n\n\u002F\u002F Differences between nextTick and setImmediate\nprocess.nextTick(() => console.log('nextTick')); \u002F\u002F runs before promise microtasks? Actually nextTick runs before microtasks in Node\nPromise.resolve().then(() => console.log('promise'));\nsetImmediate(() => console.log('immediate'));\n\u002F\u002F Output: nextTick, promise, immediate\n\n\u002F\u002F Poll phase starving\nconst start = Date.now();\nsetTimeout(() => {\n  console.log('timer:', Date.now() - start);\n}, 100);\nfs.readFile(__filename, () => {\n  const wait = Date.now();\n  while (Date.now() - wait \u003C 200) {} \u002F\u002F blocks poll phase\n});\n\u002F\u002F timer will be delayed beyond 100ms because poll phase held I\u002FO callback\n```\n\n**Execution Flow (Node.js):**\n1. **Timers**: callbacks from `setTimeout`\u002F`setInterval` (min-heap).\n2. **Pending callbacks**: I\u002FO errors, some system operations.\n3. **Idle, prepare**: internal use.\n4. **Poll**: retrieve new I\u002FO events, execute I\u002FO callbacks, block if no timers.\n5. **Check**: `setImmediate` callbacks.\n6. **Close callbacks**: `socket.on('close')`.\nBetween phases, microtasks (`nextTick` queue and promise microtasks) are processed. `nextTick` runs before promise microtasks.\n\n**Practical Usage:**\n- Use `setImmediate` for callbacks that should run after I\u002FO.\n- Use `process.nextTick` for immediate but before I\u002FO (but prefer `Promise.resolve()` or `queueMicrotask`).\n- Avoid blocking poll phase with synchronous CPU work.\n\n**Interview Insight:**\nBrowser event loop prioritizes rendering between tasks; Node.js doesn't have rendering. `setImmediate` is Node-specific (not in browsers). `process.nextTick` can starve I\u002FO if called recursively (use `setImmediate` for recursion). Event loop in Node.js also handles `Worker Threads`.\n\n**Common Mistakes:**\n- Assuming `setTimeout(fn,0)` runs before I\u002FO (depends on when timer is set).\n- Using `process.nextTick` in long loops causing event loop starvation.\n- Confusing microtask order between browsers and Node (browsers: all microtasks; Node: nextTick then promise).\n\n**Real-world Example:**\nExpress server: each request is queued; long-running synchronous code blocks event loop and degrades throughput. Use worker threads or async operations.\n\n**Advanced Notes:**\nLibuv provides thread pool for some operations (file I\u002FO, DNS). `uv_run` drives event loop. `process.nextTick` callbacks are stored in a separate queue, processed after each phase. Modern Node.js also supports `queueMicrotask` (aliases to promise microtask queue). `--inspect` can debug event loop performance.",[287,258,346,98],"libuv",{"id":348,"category":342,"question":349,"answer":350,"level":214,"tags":351},43,"Explain Node.js Streams. What are the types of streams (Readable, Writable, Duplex, Transform) and how do you handle backpressure?","**Concept Explanation:**\nStreams are Node.js's way of handling data incrementally (chunk by chunk) instead of loading everything into memory. Types: Readable (sources), Writable (destinations), Duplex (both), Transform (modify data). Backpressure occurs when writable cannot keep up with readable; handled by `pipe()` or manual `pause()`\u002F`resume()` and `drain` event.\n\n**Syntax Explanation:**\n```javascript\nconst fs = require('fs');\n\n\u002F\u002F Create readable stream\nconst readable = fs.createReadStream('large-file.txt', { encoding: 'utf8', highWaterMark: 64 * 1024 });\n\n\u002F\u002F Create writable stream\nconst writable = fs.createWriteStream('output.txt');\n\n\u002F\u002F Piping (automatic backpressure handling)\nreadable.pipe(writable);\n\n\u002F\u002F Manual backpressure handling\nreadable.on('data', (chunk) => {\n  if (!writable.write(chunk)) {\n    readable.pause(); \u002F\u002F pause when buffer full\n  }\n});\nwritable.on('drain', () => {\n  readable.resume(); \u002F\u002F resume when ready\n});\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Transform stream (uppercase)\nconst { Transform } = require('stream');\nconst upperCaseTransform = new Transform({\n  transform(chunk, encoding, callback) {\n    this.push(chunk.toString().toUpperCase());\n    callback();\n  }\n});\nreadable.pipe(upperCaseTransform).pipe(writable);\n\n\u002F\u002F Duplex stream (socket-like)\nconst { Duplex } = require('stream');\nclass MyDuplex extends Duplex {\n  _read(size) { \u002F* push data *\u002F }\n  _write(chunk, encoding, callback) { \u002F* handle write *\u002F callback(); }\n}\n\n\u002F\u002F Custom readable stream\nconst { Readable } = require('stream');\nconst counter = new Readable({\n  read(size) {\n    if (this.count === undefined) this.count = 0;\n    if (this.count \u003C 10) {\n      this.push(`${this.count++}\\n`);\n    } else {\n      this.push(null); \u002F\u002F end\n    }\n  }\n});\ncounter.pipe(process.stdout);\n\n\u002F\u002F Stream pipeline for error handling\nconst { pipeline } = require('stream');\nconst zlib = require('zlib');\npipeline(\n  fs.createReadStream('input.txt'),\n  zlib.createGzip(),\n  fs.createWriteStream('input.txt.gz'),\n  (err) => {\n    if (err) console.error('Pipeline failed', err);\n    else console.log('Success');\n  }\n);\n```\n\n**Practical Usage:**\n- Processing large files without memory overload.\n- Real-time data processing (logs, video streaming).\n- Building proxy servers or data pipelines.\n- Compression, encryption, or transformation.\n\n**Interview Insight:**\n`pipe()` automatically manages backpressure and ends destinations. `highWaterMark` controls internal buffer size. `_read()` is called when buffer is low. `_write()` is called with chunks. Backpressure signals: `write()` returns false when internal buffer exceeds highWaterMark; `drain` event indicates ready for more.\n\n**Common Mistakes:**\n- Not handling errors (use `pipeline` or `stream.on('error')`).\n- Forgetting to call `callback()` in transform or `push(null)` to end.\n- Mixing streams with callbacks without proper cleanup.\n\n**Real-world Example:**\nHTTP file download: `fs.createReadStream(file).pipe(res)` streams file to client without loading into memory. Video streaming: transform stream to chunk data based on client range requests.\n\n**Advanced Notes:**\nNode.js 15+ supports `stream\u002Fpromises` API. `finished` utility detects stream completion\u002Ferror. `pipeline` handles errors and cleanup. Object mode streams (for objects instead of buffers). `readable.read()` manual control. Backpressure can propagate through pipe chains. Streams are the foundation of many Node.js core modules (http, fs, crypto, zlib).",[352,287,353,354],"streams","backpressure","pipe",{"id":356,"category":357,"question":358,"answer":359,"level":214,"tags":360},44,"Storage APIs","Compare IndexedDB, localStorage, and sessionStorage. When would you use IndexedDB over other storage mechanisms?","**Concept Explanation:**\n- `localStorage\u002FsessionStorage`: synchronous, key-value (strings only), limited to ~5-10MB.\n- `IndexedDB`: asynchronous, supports large data (hundreds MB), indexes, transactions, complex queries, structured data (objects, blobs).\nIndexedDB is suitable for offline apps, large datasets, binary data. LocalStorage for simple preferences, sessionStorage for tab-specific temporary data.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F localStorage (sync)\nlocalStorage.setItem('theme', 'dark');\nconst theme = localStorage.getItem('theme');\n\n\u002F\u002F IndexedDB (async)\nconst request = indexedDB.open('MyDatabase', 1);\nrequest.onsuccess = (event) => {\n  const db = event.target.result;\n  const transaction = db.transaction(['store'], 'readonly');\n  const store = transaction.objectStore('store');\n  const getRequest = store.get('key');\n  getRequest.onsuccess = () => console.log(getRequest.result);\n};\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Creating IndexedDB schema\nconst openRequest = indexedDB.open('AppDB', 1);\nopenRequest.onupgradeneeded = (e) => {\n  const db = e.target.result;\n  if (!db.objectStoreNames.contains('users')) {\n    const store = db.createObjectStore('users', { keyPath: 'id' });\n    store.createIndex('email', 'email', { unique: true });\n  }\n};\n\n\u002F\u002F Adding data (async\u002Fawait wrapper)\nfunction addUser(user) {\n  return new Promise((resolve, reject) => {\n    const dbRequest = indexedDB.open('AppDB');\n    dbRequest.onsuccess = () => {\n      const db = dbRequest.result;\n      const tx = db.transaction('users', 'readwrite');\n      const store = tx.objectStore('users');\n      const addRequest = store.add(user);\n      addRequest.onsuccess = resolve;\n      addRequest.onerror = reject;\n      tx.oncomplete = () => db.close();\n    };\n  });\n}\n\n\u002F\u002F Query with index\nfunction getUserByEmail(email) {\n  const dbRequest = indexedDB.open('AppDB');\n  dbRequest.onsuccess = () => {\n    const db = dbRequest.result;\n    const tx = db.transaction('users');\n    const store = tx.objectStore('users');\n    const index = store.index('email');\n    const getRequest = index.get(email);\n    getRequest.onsuccess = () => console.log(getRequest.result);\n  };\n}\n\n\u002F\u002F Storing large binary (files)\nfunction storeFile(file) {\n  const dbRequest = indexedDB.open('FileDB');\n  dbRequest.onsuccess = () => {\n    const db = dbRequest.result;\n    const tx = db.transaction('files', 'readwrite');\n    const store = tx.objectStore('files');\n    store.put(file, file.name);\n  };\n}\n```\n\n**Practical Usage:**\n- **localStorage**: user preferences, theme, simple caching, auth tokens.\n- **sessionStorage**: temporary form drafts, scroll position recovery, one-time data.\n- **IndexedDB**: offline-first apps (PWA), large dataset caching (e.g., map tiles), file storage, complex queries, structured data.\n\n**Interview Insight:**\nIndexedDB is transactional, supports versioning, and is asynchronous (non-blocking). localStorage is synchronous and can block main thread during read\u002Fwrite. IndexedDB also works in Web Workers. For simple key-value, use `localStorage`. For search\u002Fquery, use IndexedDB.\n\n**Common Mistakes:**\n- Using IndexedDB for tiny data (overkill).\n- Blocking UI with large localStorage operations.\n- Forgetting to close database connections.\n\n**Real-world Example:**\nProgressive Web App: cache API responses in IndexedDB for offline access, store user-generated content locally, sync when online. LocalStorage for settings like dark mode.\n\n**Advanced Notes:**\nIndexedDB can store Blobs, File, ArrayBuffer. Use `localForage` library as a simple wrapper. IndexedDB API is event-based but can be promisified. `cursor` for iterating. `IDBKeyRange` for range queries. Storage limits ~50% of free disk space (prompts user).",[361,156,157,159],"indexeddb",{"id":363,"category":364,"question":365,"answer":366,"level":214,"tags":367},45,"Async Patterns","What is Promise.all, Promise.allSettled, Promise.race, and Promise.any? Provide examples and use cases.","**Concept Explanation:**\n- `Promise.all`: rejects immediately if any promise rejects; resolves with array of results (order preserved).\n- `Promise.allSettled`: waits for all promises to settle (fulfill or reject); returns array of objects `{ status, value\u002Freason }`.\n- `Promise.race`: resolves\u002Frejects with first settled promise.\n- `Promise.any`: resolves with first fulfilled promise; rejects only if all reject (AggregateError).\n\n**Syntax Explanation:**\n```javascript\nconst p1 = Promise.resolve(1);\nconst p2 = Promise.reject('error');\nconst p3 = Promise.resolve(3);\n\nPromise.all([p1, p3]).then(console.log); \u002F\u002F [1,3]\nPromise.all([p1, p2]).catch(console.error); \u002F\u002F 'error'\n\nPromise.allSettled([p1, p2, p3])\n  .then(results => console.log(results));\n\u002F\u002F [{status:'fulfilled',value:1}, {status:'rejected',reason:'error'}, ...]\n\nPromise.race([p1, p2]).then(console.log); \u002F\u002F 1\nPromise.any([p2, p1]).then(console.log); \u002F\u002F 1\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Promise.all: parallel independent requests where all needed\nasync function loadUserAndPosts(userId) {\n  const [user, posts] = await Promise.all([\n    fetch(`\u002Fuser\u002F${userId}`).then(r => r.json()),\n    fetch(`\u002Fposts?userId=${userId}`).then(r => r.json())\n  ]);\n  return { user, posts };\n}\n\n\u002F\u002F Promise.allSettled: ignore failures, get all results\nasync function checkUrls(urls) {\n  const results = await Promise.allSettled(\n    urls.map(url => fetch(url).then(r => r.status))\n  );\n  const successful = results.filter(r => r.status === 'fulfilled');\n  return successful;\n}\n\n\u002F\u002F Promise.race: timeout pattern\nfunction fetchWithTimeout(url, timeoutMs = 5000) {\n  return Promise.race([\n    fetch(url),\n    new Promise((_, reject) => \n      setTimeout(() => reject(new Error('Timeout')), timeoutMs)\n    )\n  ]);\n}\n\n\u002F\u002F Promise.any: first successful response (e.g., fastest CDN)\nconst cdnUrls = [\n  'https:\u002F\u002Fcdn1.example.com\u002Fdata.json',\n  'https:\u002F\u002Fcdn2.example.com\u002Fdata.json'\n];\nconst fastestData = await Promise.any(cdnUrls.map(url => fetch(url).then(r => r.json())));\n```\n\n**Practical Usage:**\n- `all`: multiple API calls needed for one view.\n- `allSettled`: logging\u002Fanalytics where failures are non-critical.\n- `race`: timeouts, request cancellation (with AbortController).\n- `any`: fallback servers, load balancing, redundant services.\n\n**Interview Insight:**\n`Promise.all` fails fast; `allSettled` never rejects. `any` ignores rejections until all reject. `race` unpredictable if multiple settle simultaneously. `AggregateError` (ES2021) for `Promise.any` rejection.\n\n**Common Mistakes:**\n- Using `Promise.all` when one failure shouldn't break everything.\n- Forgetting to catch `Promise.race` rejections (timeout).\n- Assuming `Promise.any` returns array (returns single value).\n\n**Real-world Example:**\nDashboard widget: fetch multiple API endpoints with `Promise.allSettled` to show partial data even if some services fail.\n\n**Advanced Notes:**\nAll methods handle non-promise values (converted via `Promise.resolve`). `Promise.allSettled` added in ES2020, `Promise.any` in ES2021. For empty arrays: `all` resolves with [], `race` never settles, `any` rejects with `AggregateError`, `allSettled` resolves with [].",[97,368,369,370,98],"promise-all","promise-race","promise-any",[372,382,389,400,406,412,421,428,437,448,456,464,470,481,491,502,511,520,532,542],{"id":373,"category":219,"question":374,"answer":375,"level":376,"tags":377},46,"How does JIT compilation work in JavaScript engines (e.g., V8)? Explain the role of Ignition, Sparkplug, and TurboFan.","**Concept Explanation:**\nModern JavaScript engines use Just-In-Time (JIT) compilation to optimize performance. V8 compiles JavaScript in multiple tiers: Ignition (interpreter), Sparkplug (baseline compiler), and TurboFan (optimizing compiler). Hot functions are optimized progressively, while cold code runs slowly. This balances startup time and peak performance.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Hot function example (will be optimized)\nfunction add(a, b) {\n  return a + b;\n}\nfor (let i = 0; i \u003C 10000; i++) add(i, i+1); \u002F\u002F becomes hot\n\n\u002F\u002F Deoptimization trigger\nfunction polyAdd(a, b) {\n  return a + b;\n}\npolyAdd(1,2); \u002F\u002F integer addition\npolyAdd(\"a\", \"b\"); \u002F\u002F string concatenation – deoptimization\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Inline caching demonstration\nfunction getName(user) {\n  return user.name;\n}\nconst alice = { name: 'Alice', role: 'admin' };\nconst bob = { name: 'Bob', role: 'user' };\nfor (let i = 0; i \u003C 1000; i++) {\n  getName(alice); \u002F\u002F same hidden class -> inline cache hit\n}\n\n\u002F\u002F Polymorphic vs monomorphic\n\u002F\u002F Monomorphic (fast): always same object shape\n\u002F\u002F Polymorphic (slower): multiple shapes\n\u002F\u002F Megamorphic (very slow): many shapes\n\n\u002F\u002F Hidden classes\nfunction Point(x, y) {\n  this.x = x;\n  this.y = y;\n}\nconst p1 = new Point(1,2); \u002F\u002F hidden class C0 -> C1 (x added) -> C2 (y added)\nconst p2 = new Point(3,4); \u002F\u002F reuses same hidden class transitions\n```\n\n**Execution Flow:**\n1. Parser generates AST → Ignition bytecode (interpreter).\n2. Execution starts in Ignition (fast startup).\n3. After function becomes hot (> calls\u002Floops threshold), Sparkplug compiles to baseline machine code.\n4. If function remains hot and types stable, TurboFan performs speculative optimization (inline caches, type specialization).\n5. If assumptions break (e.g., different argument type), deoptimization occurs, reverting to interpreter or Sparkplug.\n\n**Practical Usage:**\n- Write monomorphic functions (consistent object shapes).\n- Avoid changing object structure after creation (`delete` or adding properties).\n- Use `Array` instead of array-like objects for better optimization.\n\n**Interview Insight:**\nJIT trades off warmup time for peak performance. Hidden classes (maps) enable property access via fixed offsets. Inline caching stores resolved property locations. Deoptimization can be costly; avoid polymorphic call sites in hot paths.\n\n**Common Mistakes:**\n- Changing object shape after initialization (creates new hidden class).\n- Using `try\u002Fcatch` inside hot functions (prevents optimization in some engines).\n- Passing different types to same function parameter.\n\n**Real-world Example:**\nV8 powers Node.js and Chrome. Performance-sensitive code (game loops, real-time processing) benefits from JIT-friendly patterns: monomorphic functions, stable prototypes, integer indices for arrays.\n\n**Advanced Notes:**\nTurboFan also optimizes loops, dynamic type checks, and inlining. Sparkplug fills gap between interpreter and optimizing compiler (V8 9.0+). Liftoff (WebAssembly) similar. WebKit JavaScriptCore has LLInt, Baseline JIT, DFG JIT, FTL JIT. V8 also has Bytecode flushing for memory reduction.","advanced",[378,379,380,251,381],"v8","jit","compilation","hidden-classes",{"id":383,"category":264,"question":384,"answer":385,"level":376,"tags":386},47,"Explain garbage collection in JavaScript (mark-and-sweep, generational collection). How do memory leaks occur and how to use WeakRef and FinalizationRegistry?","**Concept Explanation:**\nJavaScript uses automatic garbage collection (GC) primarily mark-and-sweep. The GC marks reachable objects from roots (global, stack references), then sweeps unreachable ones. Generational collection separates objects into young generation (frequent, fast collection) and old generation (less frequent). `WeakRef` allows weak references without preventing GC; `FinalizationRegistry` runs callbacks when objects are collected.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Mark-and-sweep\nlet obj = { data: 'large' };\nobj = null; \u002F\u002F unreachable, will be swept\n\n\u002F\u002F Generational: short-lived objects (e.g., local variables) collected quickly\nfunction temporary() {\n  const temp = { x: 1 }; \u002F\u002F young generation\n  return temp.x;\n}\n\n\u002F\u002F WeakRef\nlet target = { name: 'Alice' };\nconst weakRef = new WeakRef(target);\ntarget = null;\nconsole.log(weakRef.deref()); \u002F\u002F undefined after GC\n\n\u002F\u002F FinalizationRegistry\nconst registry = new FinalizationRegistry((heldValue) => {\n  console.log(`Object with ${heldValue} was collected`);\n});\nlet obj2 = { data: 'important' };\nregistry.register(obj2, 'important data');\nobj2 = null; \u002F\u002F after GC, callback runs\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Memory leak: detached DOM nodes\nlet detachedDiv = document.createElement('div');\ndocument.body.appendChild(detachedDiv);\ndetachedDiv.remove();\n\u002F\u002F detachedDiv still referenced -> leak\ndetachedDiv = null; \u002F\u002F fix\n\n\u002F\u002F Using WeakMap for caching without preventing GC\nconst cache = new WeakMap();\nfunction process(obj) {\n  if (cache.has(obj)) return cache.get(obj);\n  const result = expensiveComputation(obj);\n  cache.set(obj, result);\n  return result;\n}\n\u002F\u002F When obj is no longer referenced elsewhere, it can be GCed with cache entry\n\n\u002F\u002F FinalizationRegistry for cleanup\nconst fileHandles = new FinalizationRegistry(([handle, path]) => {\n  console.log(`Closing file handle for ${path}`);\n  handle.close();\n});\nasync function openFile(path) {\n  const handle = await fs.promises.open(path);\n  const wrapper = { handle, path };\n  fileHandles.register(wrapper, [handle, path]);\n  return wrapper;\n}\n\n\u002F\u002F Avoiding premature GC with WeakRef\nfunction getCachedData(key) {\n  if (!globalCache.has(key)) return null;\n  const weakRef = globalCache.get(key);\n  const data = weakRef.deref();\n  if (!data) globalCache.delete(key);\n  return data;\n}\n```\n\n**Practical Usage:**\n- Use `WeakMap` for private data or caches tied to object lifetimes.\n- Use `FinalizationRegistry` for external resource cleanup (file handles, network connections).\n- Avoid `WeakRef` for critical logic (GC timing non-deterministic).\n\n**Interview Insight:**\nMark-and-sweep cannot detect circular references (both markable if root-reachable). Generational hypothesis: most objects die young. Scavenging (copying) for young generation, mark-compact for old generation. `WeakRef` and `FinalizationRegistry` are advanced tools for library authors, not everyday use.\n\n**Common Mistakes:**\n- Relying on `FinalizationRegistry` for critical cleanup (GC may never run).\n- Expecting `WeakRef.deref()` to always return object.\n- Overusing `FinalizationRegistry` impacting performance.\n\n**Real-world Example:**\nIn-memory cache with LRU + WeakRef: cache frequently used objects, but allow GC to collect them under memory pressure.\n\n**Advanced Notes:**\nV8 uses Orinoco (parallel, concurrent, incremental GC). `--trace-gc` flags in Node.js. `performance.memory` API (Chrome) for heap stats. `FinalizationRegistry` callbacks run in a microtask checkpoint, not immediately. `WeakRef` is useful for implementing caches or memoization without memory leaks.",[270,387,388,216],"weakref","finalizationregistry",{"id":390,"category":391,"question":392,"answer":393,"level":376,"tags":394},48,"Concurrency","How do Web Workers and SharedArrayBuffer work? Explain Atomics for synchronization and their use cases.","**Concept Explanation:**\nWeb Workers run JavaScript in background threads (no DOM access). `SharedArrayBuffer` (SAB) allows multiple workers (and main thread) to share memory. `Atomics` provide atomic operations (add, compareExchange, load, store) for lock-free synchronization, preventing race conditions. SAB requires cross-origin isolation headers (COOP\u002FCOEP).\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Main thread\nconst worker = new Worker('worker.js');\nconst sab = new SharedArrayBuffer(1024);\nconst int32 = new Int32Array(sab);\nint32[0] = 0;\nworker.postMessage(sab); \u002F\u002F transfer ownership?\n\u002F\u002F SAB can be shared (no transfer needed, but structured clone copies reference)\n\n\u002F\u002F Worker (worker.js)\nself.onmessage = (e) => {\n  const sab = e.data;\n  const int32 = new Int32Array(sab);\n  Atomics.add(int32, 0, 1); \u002F\u002F atomic increment\n  Atomics.notify(int32, 0, 1); \u002F\u002F wake waiting thread\n};\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Main thread with Atomics.wait\nconst sab = new SharedArrayBuffer(4);\nconst view = new Int32Array(sab);\nview[0] = 0;\n\nconst worker = new Worker('worker.js');\nworker.postMessage(sab);\n\nconsole.log('Waiting...');\nAtomics.wait(view, 0, 0); \u002F\u002F blocks until notified\nconsole.log('Value is', view[0]);\n\n\u002F\u002F Worker code\nself.onmessage = (e) => {\n  const view = new Int32Array(e.data);\n  setTimeout(() => {\n    Atomics.store(view, 0, 42);\n    Atomics.notify(view, 0, 1);\n  }, 1000);\n};\n\n\u002F\u002F Atomic compare-and-swap (lock implementation)\nfunction lock(mutex, index) {\n  while (true) {\n    const old = Atomics.compareExchange(mutex, index, 0, 1);\n    if (old === 0) return; \u002F\u002F acquired\n    Atomics.wait(mutex, index, 1); \u002F\u002F wait if locked\n  }\n}\nfunction unlock(mutex, index) {\n  const old = Atomics.compareExchange(mutex, index, 1, 0);\n  Atomics.notify(mutex, index, 1);\n}\n\n\u002F\u002F Simple counter without race\nlet counter = new Int32Array(new SharedArrayBuffer(4));\nfunction increment() {\n  Atomics.add(counter, 0, 1);\n}\n```\n\n**Practical Usage:**\n- High-performance parallel processing (image\u002Fvideo, audio, scientific).\n- Game physics or simulations with shared memory.\n- Real-time collaborative editing (with operational transforms).\n\n**Interview Insight:**\n`SharedArrayBuffer` was disabled due to Spectre\u002FMeltdown vulnerabilities; re-enabled with COOP\u002FCOEP headers. `Atomics` operations are atomic (hardware guarantees). `Atomics.wait` blocks the thread (only in workers, main thread cannot wait). Workers cannot block main thread.\n\n**Common Mistakes:**\n- Forgetting cross-origin isolation headers (SAB won't work).\n- Using `Atomics` without SAB (TypeError).\n- Assuming `postMessage` transfers SAB (it shares, not transfers).\n\n**Real-world Example:**\nVideo processing: split frames across workers sharing a buffer; each worker processes a region; Atomics manages progress counters.\n\n**Advanced Notes:**\n`Atomics` supports: add, sub, and, or, xor, compareExchange, exchange, load, store, wait, notify, isLockFree. `SharedArrayBuffer` can be used with TypedArrays and DataView. Web Workers also support `transfer` for ArrayBuffer (moves ownership). Chrome requires `--enable-blink-features=SharedArrayBuffer` flag without headers. Node.js supports SAB with `--experimental-sharedarraybuffer`.",[395,396,397,398,399],"web-workers","sharedarraybuffer","atomics","concurrency","threads",{"id":401,"category":245,"question":402,"answer":403,"level":376,"tags":404},49,"Explain inline caching and hidden classes in JavaScript engines. How do they optimize property access and what coding patterns should you follow?","**Concept Explanation:**\nHidden classes (maps) are internal structures that track object shape (property names and order). Inline caching (IC) stores the hidden class and property offset at a call site, skipping expensive lookup on subsequent calls. Monomorphic IC (same hidden class) is fastest; polymorphic (few classes) slower; megamorphic (many classes) falls back to dictionary mode.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Monomorphic: same shape\nfunction getX(obj) { return obj.x; }\nconst a = { x: 1, y: 2 };\nconst b = { x: 3, y: 4 };\ngetX(a); getX(b); \u002F\u002F same hidden class -> IC hit\n\n\u002F\u002F Polymorphic: two shapes\nconst c = { x: 5, z: 6 }; \u002F\u002F different property order\ngetX(c); \u002F\u002F new IC entry (polymorphic, up to 4-8 shapes)\n\n\u002F\u002F Megamorphic: many shapes\nconst objs = [];\nfor (let i = 0; i \u003C 100; i++) {\n  const o = {};\n  o[`prop${i}`] = i; \u002F\u002F each object unique shape\n  objs.push(o);\n}\nobjs.forEach(o => getX(o)); \u002F\u002F megamorphic, slow\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Good pattern: initialize all properties in constructor\nclass Point {\n  constructor(x, y) {\n    this.x = x; \u002F\u002F order fixed\n    this.y = y;\n  }\n}\n\n\u002F\u002F Bad pattern: adding properties after creation\nconst p = new Point(1,2);\np.z = 3; \u002F\u002F new hidden class, deoptimizes previous ICs\n\n\u002F\u002F Avoid deleting properties\ndelete p.y; \u002F\u002F changes hidden class, causes transition\n\u002F\u002F Better: set to undefined or null\np.y = undefined;\n\n\u002F\u002F Array optimization: use dense arrays\nconst arr = [1,2,3]; \u002F\u002F dense, fast\narr[1000] = 1; \u002F\u002F becomes sparse\u002Fholey, slower\n\n\u002F\u002F Use monomorphic functions\nfunction process(user) {\n  return user.name + user.age; \u002F\u002F consistent shape\n}\n\n\u002F\u002F Avoid changing prototypes at runtime\nfunction Animal() {}\nAnimal.prototype.speak = function() {};\nconst dog = new Animal();\n\u002F\u002F Later:\nAnimal.prototype.walk = function() {}; \u002F\u002F changes hidden class of existing instances? Actually affects prototype chain\n```\n\n**Practical Usage:**\n- Define all object properties in constructor (same order).\n- Avoid `delete` and dynamic property addition after initialization.\n- Keep object shapes consistent across instances.\n- Use classes or factory functions that produce identical shapes.\n\n**Interview Insight:**\nHidden classes are not JavaScript feature but engine optimization. They enable property access via fixed offset (like C++ struct). Inline caching stores up to 4-8 polymorphic states before becoming megamorphic. For performance-critical code, keep call sites monomorphic.\n\n**Common Mistakes:**\n- Using objects as dictionaries (use `Map` instead).\n- Adding properties conditionally (`if (cond) obj.prop = value`).\n- Creating many objects with different shapes (e.g., JSON.parse creates objects with varying keys).\n\n**Real-world Example:**\nReact components with props: keep prop shapes consistent across renders. Avoid spreading dynamic keys into component props.\n\n**Advanced Notes:**\nV8 has a limit of ~1024 unique hidden classes per site before degrading to dictionary mode. `%DebugPrint` in V8 flags. Hidden classes also apply to arrays (elements kind: packed\u002Fsmi\u002Fdouble\u002Fholey). Inline caching also works for function calls (method caching). Turbofan uses IC feedback for speculative optimization.",[405,381,378,251],"inline-caching",{"id":407,"category":219,"question":408,"answer":409,"level":376,"tags":410},50,"How does the event loop interact with the microtask and macrotask queues in different environments (browser vs Node.js)? Explain event loop starvation.","**Concept Explanation:**\nThe event loop continuously checks call stack, then microtask queue (promises, `queueMicrotask`), then macrotask queue (setTimeout, I\u002FO). Browsers interleave rendering (requestAnimationFrame, paint) between macrotasks. Node.js has phases (timers, I\u002FO, check). Starvation occurs when microtasks are continuously added, preventing macrotasks or rendering from executing.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Browser: microtask starvation\nfunction starve() {\n  Promise.resolve().then(starve); \u002F\u002F infinite microtask recursion\n}\nstarve();\nsetTimeout(() => console.log('never runs'), 0); \u002F\u002F macrotask starved\n\n\u002F\u002F Node.js: nextTick starvation\nfunction nodeStarve() {\n  process.nextTick(nodeStarve); \u002F\u002F higher priority than promise microtasks\n}\nnodeStarve();\nsetImmediate(() => console.log('never runs'));\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Browser event loop with rendering\nbutton.addEventListener('click', () => {\n  setTimeout(() => {\n    document.body.style.backgroundColor = 'red';\n  }, 0);\n  Promise.resolve().then(() => {\n    document.body.style.backgroundColor = 'green';\n  });\n});\n\u002F\u002F Result: green briefly, then red (microtask before render, macrotask after)\n\n\u002F\u002F Node.js event loop phases\nconst fs = require('fs');\nfs.readFile(__filename, () => {\n  console.log('I\u002FO');\n  setImmediate(() => console.log('immediate'));\n  setTimeout(() => console.log('timeout'), 0);\n  process.nextTick(() => console.log('nextTick'));\n});\n\u002F\u002F Output order: I\u002FO, nextTick, immediate, timeout\n\u002F\u002F (nextTick runs after I\u002FO phase, before check phase)\n\n\u002F\u002F Simulating microtask starvation mitigation\nlet count = 0;\nfunction safeRecursive() {\n  count++;\n  if (count % 1000 === 0) {\n    setTimeout(() => safeRecursive(), 0); \u002F\u002F yield to macrotasks\n  } else {\n    Promise.resolve().then(safeRecursive);\n  }\n}\n\n\u002F\u002F Node.js: setImmediate vs setTimeout\nsetImmediate(() => console.log('immediate'));\nsetTimeout(() => console.log('timeout'), 0);\n\u002F\u002F Order depends on event loop state (timeout may execute before immediate if poll phase has timers)\n```\n\n**Practical Usage:**\n- Use microtasks for operations that should happen before next task (batching).\n- Avoid recursive microtask scheduling.\n- In Node.js, prefer `setImmediate` over `setTimeout(fn,0)` for deferring I\u002FO.\n\n**Interview Insight:**\nIn browsers, microtask checkpoint happens after every macrotask (and after JS stack empties). Rendering occurs before next macrotask but after microtasks. Node.js `process.nextTick` is not a microtask (runs before promise microtasks). Node.js microtask queue is between phases; `nextTick` queue has higher priority.\n\n**Common Mistakes:**\n- Starving event loop with infinite promise chain.\n- Assuming `setTimeout(fn,0)` ordering is deterministic across environments.\n- Using `while` loop with async conditions (blocks event loop).\n\n**Real-world Example:**\nPromise implementation that recursively uses `then` to schedule itself can starve UI. Libraries like Redux use microtasks for batching but may need to yield with `setTimeout` for long operations.\n\n**Advanced Notes:**\n`queueMicrotask` standard API for microtasks. In Node.js, `process.nextTick` can starve; use `setImmediate` for recursion. The event loop in Node.js also has `ref()`\u002F`unref()` to control active handles. Browser `requestIdleCallback` for low-priority tasks. Event loop lag can be measured via performance event timing.",[258,260,261,287,411],"browser",{"id":413,"category":219,"question":414,"answer":415,"level":376,"tags":416},51,"What are Proxies and Reflect in JavaScript? Explain advanced use cases like validation, logging, and reactive systems.","**Concept Explanation:**\n`Proxy` allows intercepting and customizing operations on objects (get, set, delete, etc.). `Reflect` provides default behavior for these operations, often used inside proxy handlers. Proxies enable metaprogramming: validation, logging, reactive systems (Vue 3, MobX), and virtual objects.\n\n**Syntax Explanation:**\n```javascript\nconst target = { name: 'Alice', age: 30 };\nconst handler = {\n  get(obj, prop) {\n    if (prop === 'age') return obj[prop] + ' years';\n    return Reflect.get(obj, prop);\n  },\n  set(obj, prop, value) {\n    if (prop === 'age' && (value \u003C 0 || value > 150)) {\n      throw new Error('Invalid age');\n    }\n    return Reflect.set(obj, prop, value);\n  }\n};\nconst proxy = new Proxy(target, handler);\nconsole.log(proxy.age); \u002F\u002F '30 years'\nproxy.age = 200; \u002F\u002F Error\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Validation proxy\nfunction createValidator(schema) {\n  return new Proxy({}, {\n    set(target, prop, value) {\n      if (schema[prop] && !schema[prop](value)) {\n        throw new Error(`Invalid ${prop}: ${value}`);\n      }\n      target[prop] = value;\n      return true;\n    }\n  });\n}\nconst user = createValidator({\n  name: v => typeof v === 'string' && v.length > 0,\n  age: v => Number.isInteger(v) && v >= 0\n});\nuser.name = 'Bob'; \u002F\u002F OK\nuser.age = -5; \u002F\u002F Error\n\n\u002F\u002F Logging proxy (debugging)\nconst logged = new Proxy(target, {\n  get(obj, prop) {\n    console.log(`GET ${String(prop)}`);\n    return Reflect.get(obj, prop);\n  },\n  set(obj, prop, value) {\n    console.log(`SET ${String(prop)} = ${value}`);\n    return Reflect.set(obj, prop, value);\n  }\n});\n\n\u002F\u002F Reactive system (simple)\nfunction reactive(obj) {\n  const listeners = new Map();\n  return new Proxy(obj, {\n    set(target, prop, value) {\n      const old = target[prop];\n      if (Reflect.set(target, prop, value)) {\n        if (listeners.has(prop)) {\n          listeners.get(prop).forEach(fn => fn(value, old));\n        }\n        return true;\n      }\n      return false;\n    }\n  });\n}\n\n\u002F\u002F Revocable proxy\nconst { proxy: revocable, revoke } = Proxy.revocable(target, {});\nrevoke();\n\u002F\u002F revocable.name -> TypeError\n\n\u002F\u002F Proxy for negative array indices\nconst arrayProxy = new Proxy([1,2,3,4,5], {\n  get(target, prop) {\n    const index = parseInt(prop);\n    if (isNaN(index)) return Reflect.get(target, prop);\n    if (index \u003C 0) return target[target.length + index];\n    return target[index];\n  }\n});\nconsole.log(arrayProxy[-1]); \u002F\u002F 5\n```\n\n**Practical Usage:**\n- Validation and sanitization.\n- Tracing\u002Flogging for debugging.\n- Reactive data binding (Vue 3 reactivity).\n- Lazy loading or virtual properties.\n- Implementing negative array indices or other DSLs.\n\n**Interview Insight:**\n`Proxy` has 13 traps: get, set, has, deleteProperty, ownKeys, apply, construct, etc. `Reflect` provides default implementations; always use `Reflect` in proxy traps to preserve invariants. Proxies cannot be polyfilled fully (performance trade-offs).\n\n**Common Mistakes:**\n- Forgetting to return boolean in `set` trap (must return true\u002Ffalse).\n- Modifying target directly without using `Reflect` (bypasses traps).\n- Performance overhead for hot code (use only when needed).\n\n**Real-world Example:**\nVue 3 uses Proxies for reactive data; MobX uses Proxies for observable objects. Form validation libraries intercept set operations.\n\n**Advanced Notes:**\nProxy invariants: `get` for non-configurable non-writable property must return correct value. `ownKeys` must return keys consistent with target. Proxies can wrap functions (`apply` trap) and constructors (`construct` trap). `Proxy.revocable` for temporary access. `WeakRef` cannot be proxied directly.",[417,418,419,420],"proxy","reflect","metaprogramming","reactive",{"id":422,"category":423,"question":424,"answer":425,"level":376,"tags":426},52,"Async Architecture","How would you implement a custom Promise from scratch? Explain the core components (resolve, reject, then, chaining).","**Concept Explanation:**\nA Promise is a state machine (pending, fulfilled, rejected) with a `then` method that queues callbacks. Implementation requires handling asynchronous resolution, chaining (returning new Promise), and microtask scheduling. Key parts: internal state, value\u002Freason, arrays of onFulfilled\u002FonRejected callbacks, and `resolve`\u002F`reject` functions.\n\n**Syntax Explanation:**\n```javascript\nclass MyPromise {\n  constructor(executor) {\n    this.state = 'pending';\n    this.value = undefined;\n    this.callbacks = [];\n    const resolve = (value) => this._resolve(value);\n    const reject = (reason) => this._reject(reason);\n    try { executor(resolve, reject); } catch(e) { reject(e); }\n  }\n  then(onFulfilled, onRejected) {\n    return new MyPromise((resolve, reject) => {\n      this._handle({ onFulfilled, onRejected, resolve, reject });\n    });\n  }\n}\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Full minimal implementation\nclass MyPromise {\n  constructor(executor) {\n    this.state = 'pending';\n    this.value = undefined;\n    this.onFulfilledCallbacks = [];\n    this.onRejectedCallbacks = [];\n\n    const resolve = (value) => {\n      if (this.state !== 'pending') return;\n      if (value instanceof MyPromise) {\n        value.then(resolve, reject);\n        return;\n      }\n      this.state = 'fulfilled';\n      this.value = value;\n      this.onFulfilledCallbacks.forEach(fn => this._scheduleMicrotask(fn, this.value));\n    };\n\n    const reject = (reason) => {\n      if (this.state !== 'pending') return;\n      this.state = 'rejected';\n      this.value = reason;\n      this.onRejectedCallbacks.forEach(fn => this._scheduleMicrotask(fn, this.value));\n    };\n\n    try {\n      executor(resolve, reject);\n    } catch (err) {\n      reject(err);\n    }\n  }\n\n  _scheduleMicrotask(fn, value) {\n    queueMicrotask(() => {\n      try {\n        const result = fn(value);\n        this._resolvePromise(this.pendingPromise, result, this._resolve, this._reject);\n      } catch (err) {\n        this._reject(err);\n      }\n    });\n  }\n\n  then(onFulfilled, onRejected) {\n    const promise = new MyPromise((resolve, reject) => {\n      this._handle({\n        onFulfilled: onFulfilled || (val => val),\n        onRejected: onRejected || (err => { throw err; }),\n        resolve,\n        reject\n      });\n    });\n    return promise;\n  }\n\n  _handle(handler) {\n    if (this.state === 'pending') {\n      this.onFulfilledCallbacks.push(() => {\n        this._runHandler(handler.onFulfilled, handler.resolve, handler.reject, this.value);\n      });\n      this.onRejectedCallbacks.push(() => {\n        this._runHandler(handler.onRejected, handler.resolve, handler.reject, this.value);\n      });\n    } else if (this.state === 'fulfilled') {\n      this._runHandler(handler.onFulfilled, handler.resolve, handler.reject, this.value);\n    } else {\n      this._runHandler(handler.onRejected, handler.resolve, handler.reject, this.value);\n    }\n  }\n\n  _runHandler(callback, resolve, reject, value) {\n    queueMicrotask(() => {\n      try {\n        const result = callback(value);\n        this._resolvePromise(resolve, reject, result);\n      } catch (err) {\n        reject(err);\n      }\n    });\n  }\n\n  _resolvePromise(resolve, reject, result) {\n    if (result instanceof MyPromise) {\n      result.then(resolve, reject);\n    } else {\n      resolve(result);\n    }\n  }\n\n  catch(onRejected) {\n    return this.then(null, onRejected);\n  }\n\n  finally(onFinally) {\n    return this.then(\n      val => MyPromise.resolve(onFinally()).then(() => val),\n      err => MyPromise.resolve(onFinally()).then(() => { throw err; })\n    );\n  }\n\n  static resolve(value) {\n    return new MyPromise(resolve => resolve(value));\n  }\n\n  static reject(reason) {\n    return new MyPromise((_, reject) => reject(reason));\n  }\n}\n```\n\n**Execution Flow:**\n1. Executor runs synchronously; `resolve`\u002F`reject` change state and queue callbacks.\n2. `then` returns new Promise and stores handlers.\n3. When promise settles, handlers are queued as microtasks.\n4. Callback results are resolved, enabling chaining.\n\n**Practical Usage:**\n- Understanding implementation helps debug promise chains.\n- Polyfill for older environments.\n- Custom async patterns (e.g., cancellable promises).\n\n**Interview Insight:**\nThe Promises\u002FA+ specification defines behavior for interoperation. Key points: then must return a promise; onFulfilled\u002FonRejected must be called asynchronously (microtask). Chaining unwraps nested promises.\n\n**Common Mistakes:**\n- Forgetting to handle executor errors.\n- Not queueing callbacks as microtasks (synchronous execution breaks spec).\n- Not unwrapping thenable objects.\n\n**Real-world Example:**\nLibraries like Bluebird extend Promise with additional methods (map, each, delay). Understanding core implementation helps with debugging.\n\n**Advanced Notes:**\nPromises use the microtask queue (not macrotask). `queueMicrotask` polyfill uses `Promise.resolve().then()`. `resolve` must handle thenable objects (duck typing). `Promise.resolve` on a promise returns the same instance.",[97,98,427,260],"implementation",{"id":429,"category":219,"question":430,"answer":431,"level":376,"tags":432},53,"What are polyfills and transpilers? Explain how Babel works (AST, transforms, and polyfill injection).","**Concept Explanation:**\nPolyfills are pieces of code that implement modern JavaScript features in older environments. Transpilers (like Babel) convert modern syntax to equivalent older syntax. Babel parses code into AST (Abstract Syntax Tree), transforms nodes, then generates code. Core-js provides polyfills for language features; Babel can inject them conditionally.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Modern syntax\nconst sum = (a, b) => a + b;\nconst obj = { a: 1, b: 2 };\nconst { a, b } = obj;\n\n\u002F\u002F After Babel transpilation (ES5)\nvar sum = function(a, b) { return a + b; };\nvar obj = { a: 1, b: 2 };\nvar a = obj.a;\nvar b = obj.b;\n\n\u002F\u002F Polyfill for Promise\nif (typeof Promise === 'undefined') {\n  global.Promise = MyPromise; \u002F\u002F custom implementation\n}\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Babel plugin example (simplified transformation)\n\u002F\u002F Input: let x = () => 42;\n\u002F\u002F Output: var x = function() { return 42; };\nconst babel = require('@babel\u002Fcore');\nconst code = 'let x = () => 42;';\nconst output = babel.transformSync(code, {\n  plugins: [\n    function() {\n      return {\n        visitor: {\n          ArrowFunctionExpression(path) {\n            path.replaceWith(t.functionExpression(\n              null,\n              path.node.params,\n              t.blockStatement([t.returnStatement(path.node.body)])\n            ));\n          }\n        }\n      };\n    }\n  ]\n});\n\n\u002F\u002F Polyfill detection pattern\nfunction polyfillPromise() {\n  if (typeof window.Promise === 'undefined') {\n    window.Promise = MyPromise;\n  }\n}\n\n\u002F\u002F core-js usage (regenerator-runtime for async\u002Fawait)\nimport 'core-js\u002Fstable';\nimport 'regenerator-runtime\u002Fruntime';\n\n\u002F\u002F Babel preset-env with useBuiltIns: 'usage'\n\u002F\u002F Automatically adds imports for used features based on target browsers\n```\n\n**AST Example:**\n```javascript\n\u002F\u002F Code: const answer = 42;\n\u002F\u002F AST simplified:\n{\n  type: 'VariableDeclaration',\n  kind: 'const',\n  declarations: [{\n    type: 'VariableDeclarator',\n    id: { type: 'Identifier', name: 'answer' },\n    init: { type: 'NumericLiteral', value: 42 }\n  }]\n}\n```\n\n**Execution Flow (Babel):**\n1. Parse source code → AST.\n2. Traverse AST, visit nodes.\n3. Apply plugins that modify AST (transformations).\n4. Generate code from transformed AST.\n5. Optionally inject polyfills (`core-js`, `regenerator-runtime`).\n\n**Practical Usage:**\n- Support older browsers while writing modern code.\n- Use `@babel\u002Fpreset-env` with browserslist config.\n- `useBuiltIns: 'usage'` adds minimal polyfills.\n\n**Interview Insight:**\nBabel can transpile syntax (arrow functions, classes, optional chaining) but needs polyfills for new APIs (Promise, Array.includes, Object.assign). `@babel\u002Fplugin-transform-runtime` avoids polluting global scope. AST manipulation is powerful for custom transformations.\n\n**Common Mistakes:**\n- Including whole core-js (bloats bundle) instead of usage detection.\n- Forgetting to polyfill regenerator-runtime for async\u002Fawait.\n- Not configuring browserslist causing unnecessary transpilation.\n\n**Real-world Example:**\nCreate React App uses Babel to transpile JSX, modern syntax, and inject polyfills based on browser support.\n\n**Advanced Notes:**\nBabel 7+ supports TypeScript, Flow. `@babel\u002Fpreset-env` uses core-js@3. Babel macros for compile-time optimizations. SWC and esbuild are faster alternatives (written in Rust\u002FGo). Polyfills can be loaded conditionally via dynamic `import()`.",[433,434,435,436,380],"babel","polyfills","transpiler","ast",{"id":438,"category":439,"question":440,"answer":441,"level":376,"tags":442},54,"Architecture Patterns","Explain module bundling internals (Webpack, Vite). How do they resolve dependencies, handle code splitting, and optimize production builds?","**Concept Explanation:**\nModule bundlers analyze dependency graph starting from entry points, resolve module paths, transform code (loaders), then combine into bundles. Webpack uses chunk graph and runtime; Vite leverages native ES modules in dev (no bundling) and pre-bundles with Rollup for production. Code splitting creates separate chunks (dynamic imports, shared vendors). Optimization includes minification, tree shaking, and scope hoisting.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Webpack configuration\nmodule.exports = {\n  entry: '.\u002Fsrc\u002Findex.js',\n  output: { filename: 'bundle.js' },\n  module: { rules: [ { test: \u002F\\.js$\u002F, use: 'babel-loader' } ] },\n  optimization: {\n    splitChunks: { chunks: 'all' },\n    minimize: true\n  }\n};\n\n\u002F\u002F Code splitting (dynamic import)\nimport('.\u002Fmodule.js').then(module => {\n  module.default();\n});\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Simplified bundler dependency resolution\nconst fs = require('fs');\nconst path = require('path');\n\nfunction resolveDependency(filename, basedir) {\n  const extensions = ['', '.js', '.json'];\n  for (const ext of extensions) {\n    const fullPath = path.resolve(basedir, filename + ext);\n    if (fs.existsSync(fullPath)) return fullPath;\n  }\n  \u002F\u002F node_modules resolution omitted for brevity\n}\n\nfunction buildGraph(entry) {\n  const graph = {};\n  function traverse(file) {\n    const code = fs.readFileSync(file, 'utf-8');\n    const dependencies = [];\n    const regex = \u002Frequire\\(['\"]([^'\"]+)['\"]\\)\u002Fg;\n    let match;\n    while ((match = regex.exec(code))) {\n      dependencies.push(resolveDependency(match[1], path.dirname(file)));\n    }\n    graph[file] = { code, dependencies };\n    dependencies.forEach(traverse);\n  }\n  traverse(entry);\n  return graph;\n}\n\n\u002F\u002F Tree shaking (ES modules)\n\u002F\u002F math.js\nexport const add = (a,b) => a+b;\nexport const unused = (a,b) => a-b;\n\u002F\u002F main.js\nimport { add } from '.\u002Fmath.js';\n\u002F\u002F unused is eliminated\n\n\u002F\u002F Scope hoisting (concatenate modules)\n\u002F\u002F Webpack's ModuleConcatenationPlugin merges modules into single scope\n```\n\n**Practical Usage:**\n- Webpack: complex SPAs, large ecosystems, extensive configuration.\n- Vite: modern dev server (instant HMR), simpler config, faster builds.\n- Configure `optimization.splitChunks` to avoid duplicate dependencies.\n- Use dynamic imports for route-based code splitting.\n\n**Interview Insight:**\nBundlers use strategies: Webpack wraps each module in function, Vite uses native ESM during dev. Code splitting creates async chunks loaded on demand. Tree shaking relies on static ES module structure. Production optimizations include minification (Terser), CSS extraction, asset hashing for cache busting.\n\n**Common Mistakes:**\n- Over-splitting chunks (many HTTP requests).\n- Not configuring splitChunks for vendor bundles.\n- Side effects preventing tree shaking (set `sideEffects: false` in package.json).\n\n**Real-world Example:**\nReact app with lazy loading: `const LazyComponent = React.lazy(() => import('.\u002FHeavyComponent'))` generates separate chunk loaded when component renders.\n\n**Advanced Notes:**\nWebpack uses `enhanced-resolve`; Vite uses `esbuild` for pre-bundling. Module Federation (Webpack 5) enables micro-frontends. Vite's HMR preserves state. Rspack is Rust-based Webpack alternative. Turbopack (Webpack successor) incremental computation.",[443,444,445,446,447],"webpack","vite","module-bundling","code-splitting","tree-shaking",{"id":449,"category":450,"question":451,"answer":452,"level":376,"tags":453},55,"Node.js Internals","How does the libuv thread pool work in Node.js? Explain how it handles async I\u002FO and which operations use the pool vs native async.","**Concept Explanation:**\nlibuv provides asynchronous I\u002FO. Network I\u002FO (sockets, HTTP) uses native OS async interfaces (epoll, kqueue, IOCP). File system operations, DNS lookup, compression (zlib), and crypto (pbkdf2) use a thread pool (default 4 threads). The pool executes blocking tasks, then triggers callbacks in event loop via polling.\n\n**Syntax Explanation:**\n```javascript\nconst fs = require('fs');\nconst crypto = require('crypto');\n\n\u002F\u002F These use thread pool\nfs.readFile('file.txt', (err, data) => {}); \u002F\u002F file I\u002FO\ncrypto.pbkdf2('password', 'salt', 100000, 64, 'sha512', (err, key) => {}); \u002F\u002F CPU-bound\n\n\u002F\u002F This uses native async (libuv) - no pool\nconst server = require('http').createServer();\nserver.listen(3000); \u002F\u002F socket\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Thread pool size configuration\nprocess.env.UV_THREADPOOL_SIZE = 8;\nconst { threadPoolSize } = require('node:worker_threads');\nconsole.log(threadPoolSize); \u002F\u002F 8\n\n\u002F\u002F Blocking thread pool example\nconst crypto = require('crypto');\nconst start = Date.now();\nfor (let i = 0; i \u003C 10; i++) {\n  crypto.pbkdf2('a', 'b', 100000, 512, 'sha512', () => {\n    console.log(`Done in ${Date.now() - start}ms`);\n  });\n}\n\u002F\u002F With pool size 4, first 4 run quickly, next 6 wait\n\n\u002F\u002F Customizing thread pool for fs operations\nconst { Worker } = require('worker_threads');\n\u002F\u002F For CPU-intensive tasks, use worker threads instead of blocking pool\n\n\u002F\u002F Detecting thread pool blocked\nconst start = Date.now();\nfs.readFile('file.txt', () => console.log('fs'));\ncrypto.pbkdf2Sync('a','b',1,32,'sha512'); \u002F\u002F synchronous, blocks pool\nsetTimeout(() => console.log('timeout'), 0);\n\u002F\u002F 'fs' will wait until pbkdf2Sync completes\n```\n\n**Execution Flow:**\n1. JavaScript calls `fs.readFile` -> Node.js binding -> libuv.\n2. libuv creates or finds available thread in pool.\n3. Thread performs blocking file read.\n4. When done, thread posts completion to event loop's pending callbacks queue.\n5. Event loop executes callback on main thread.\n\n**Practical Usage:**\n- Increase `UV_THREADPOOL_SIZE` for heavy I\u002FO apps (careful with memory).\n- Use `worker_threads` for CPU-intensive work (isolated threads).\n- Offload blocking operations to pool (fs, crypto, zlib).\n\n**Interview Insight:**\nThe thread pool prevents event loop blocking. However, if all threads are busy, subsequent async calls are queued. Network operations never use thread pool (they're truly async). `crypto.pbkdf2`, `crypto.randomBytes` (sync version blocks). `fs.stat` also uses pool.\n\n**Common Mistakes:**\n- Synchronous versions (e.g., `readFileSync`) block the main thread AND tie up the pool? Actually sync versions block calling thread, not using pool.\n- Setting pool size too high causing thread contention.\n- Assuming all async operations are non-blocking.\n\n**Real-world Example:**\nExpress server with file upload: each upload may use pool thread; too many concurrent uploads may starve other operations.\n\n**Advanced Notes:**\nlibuv also handles signal handling, child process management, and `setTimeout`\u002F`setInterval`. Windows uses IOCP; Linux uses epoll; macOS uses kqueue. `UV_THREADPOOL_SIZE` can be set up to 128 (or more). Worker threads have their own libuv loop and thread pool. `libuv` can be embedded in other languages (Python, Rust).",[346,287,454,455],"thread-pool","async-io",{"id":457,"category":342,"question":458,"answer":459,"level":376,"tags":460},56,"How does the Node.js cluster module work? Explain multi-process architecture, load balancing, and differences from worker threads.","**Concept Explanation:**\n`cluster` module allows forking multiple child processes (workers) that share server ports. Master process manages workers and distributes incoming connections (round-robin or OS-based). This maximizes CPU utilization on multi-core systems. Worker threads provide concurrency within a single process (shared memory), while cluster provides process isolation (no shared memory).\n\n**Syntax Explanation:**\n```javascript\nconst cluster = require('cluster');\nconst http = require('http');\nconst numCPUs = require('os').cpus().length;\n\nif (cluster.isMaster) {\n  console.log(`Master ${process.pid} running`);\n  for (let i = 0; i \u003C numCPUs; i++) cluster.fork();\n  cluster.on('exit', (worker) => console.log(`Worker ${worker.process.pid} died`));\n} else {\n  http.createServer((req, res) => {\n    res.writeHead(200);\n    res.end('Hello World\\n');\n  }).listen(8000);\n  console.log(`Worker ${process.pid} started`);\n}\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Zero-downtime restart\nconst cluster = require('cluster');\nif (cluster.isMaster) {\n  const workers = [];\n  const restartWorker = (workerIndex) => {\n    const worker = workers[workerIndex];\n    worker.disconnect(); \u002F\u002F stop accepting new connections\n    worker.on('disconnect', () => {\n      const newWorker = cluster.fork();\n      workers[workerIndex] = newWorker;\n    });\n  };\n  \u002F\u002F Graceful shutdown of worker\n} else {\n  process.on('SIGTERM', () => {\n    server.close(() => process.exit());\n  });\n}\n\n\u002F\u002F IPC messaging between master and workers\n\u002F\u002F Master\ncluster.on('online', (worker) => {\n  worker.send('Hello worker');\n});\ncluster.workers[workerId].on('message', (msg) => {});\n\u002F\u002F Worker\nprocess.on('message', (msg) => {});\nprocess.send({ type: 'ready' });\n\n\u002F\u002F Custom load balancing (e.g., sticky sessions)\n\u002F\u002F Using express-session with cluster requires session store (Redis)\n\n\u002F\u002F Worker threads vs Cluster\nconst { Worker } = require('worker_threads');\nconst worker = new Worker(`\n  const { parentPort } = require('worker_threads');\n  parentPort.on('message', (data) => {\n    parentPort.postMessage({ result: data.x * 2 });\n  });\n`, { eval: true });\n```\n\n**Execution Flow:**\n1. Master process forks workers using `child_process.fork`.\n2. Each worker listens on same port (master handles port forwarding).\n3. Incoming connections are distributed via round-robin (default on Linux) or OS balancing.\n4. Workers are independent (crash doesn't affect others).\n5. Master can respawn failed workers.\n\n**Practical Usage:**\n- Maximize throughput on multi-core servers.\n- Graceful restart and zero-downtime deployments.\n- Isolate requests for stability.\n\n**Interview Insight:**\nCluster uses `child_process.fork`, not `worker_threads`. Workers cannot share memory (use Redis or IPC). `cluster.schedulingPolicy` to change algorithm (`SCHED_RR` for round-robin, `SCHED_NONE` for OS). Socket.io requires sticky sessions; use `sticky` library or redis adapter.\n\n**Common Mistakes:**\n- Not handling worker crashes (should respawn).\n- Using in-memory sessions (breaks across workers).\n- Forking too many workers (CPU cores + maybe 1).\n- Blocking event loop in worker still blocks that worker (but others handle requests).\n\n**Real-world Example:**\nProduction Express apps often use PM2 (process manager) which implements cluster mode with automatic restart and load balancing.\n\n**Advanced Notes:**\n`worker_threads` share memory (via SharedArrayBuffer) and are lighter weight (no separate event loop instance). Cluster processes have independent memory spaces. `cluster` uses `round-robin` on Linux, `OS handle` on Windows. You can also use `net` module to create custom balancer. Node.js 17+ supports `--inspect` for each worker with `--inspect=port`.",[461,287,462,463],"cluster","multi-process","load-balancing",{"id":465,"category":466,"question":467,"answer":468,"level":376,"tags":469},57,"Backpressure & Streams","Explain backpressure in Node.js streams. How does pipe() handle it and how to implement custom backpressure handling?","**Concept Explanation:**\nBackpressure occurs when a writable stream cannot process data as fast as a readable stream produces it. Without handling, memory grows unbounded. Node.js streams automatically manage backpressure via internal buffers and `pipe()` method. The `readable.pause()`\u002F`resume()` and `write()` return value (false when buffer high) with `drain` event enable manual control.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Automatic backpressure with pipe\nreadable.pipe(writable); \u002F\u002F handles pause\u002Fresume\u002Fdrain\n\n\u002F\u002F Manual backpressure\nreadable.on('data', (chunk) => {\n  const canContinue = writable.write(chunk);\n  if (!canContinue) {\n    readable.pause();\n    writable.once('drain', () => readable.resume());\n  }\n});\n```\n\n**Code Examples:**\n```javascript\nconst { Readable, Writable } = require('stream');\n\n\u002F\u002F Fast readable, slow writable\nconst fastRead = new Readable({\n  read(size) {\n    for (let i = 0; i \u003C 1000; i++) this.push(Buffer.alloc(1024, 'data'));\n  }\n});\n\nconst slowWrite = new Writable({\n  highWaterMark: 16 * 1024, \u002F\u002F 16KB buffer\n  write(chunk, encoding, callback) {\n    setTimeout(callback, 100); \u002F\u002F slow processing\n  }\n});\n\n\u002F\u002F Manual backpressure handling with highWaterMark check\nlet paused = false;\nfastRead.on('data', (chunk) => {\n  const canWrite = slowWrite.write(chunk);\n  if (!canWrite && !paused) {\n    paused = true;\n    fastRead.pause();\n    slowWrite.once('drain', () => {\n      paused = false;\n      fastRead.resume();\n    });\n  }\n});\n\n\u002F\u002F Using pipeline (recommended for error handling)\nconst { pipeline } = require('stream');\npipeline(fastRead, slowWrite, (err) => {\n  if (err) console.error('Pipeline failed', err);\n});\n\n\u002F\u002F Custom backpressure in transform stream\nconst throttleTransform = new Transform({\n  transform(chunk, enc, cb) {\n    \u002F\u002F Simulate slow processing, but let stream handle backpressure\n    setTimeout(() => cb(null, chunk), 100);\n  },\n  highWaterMark: 64 * 1024\n});\n```\n\n**Practical Usage:**\n- File copy with progress: handle backpressure to avoid OOM.\n- HTTP uploads with validation: pause parsing when downstream busy.\n- Real-time data processing: buffer management.\n\n**Interview Insight:**\n`pipe()` automatically calls `pause()` when `write()` returns false, and `resume()` on `drain`. `highWaterMark` sets internal buffer size. Backpressure propagates through pipe chain. If a stream in the middle is slow, it will backpressure the upstream.\n\n**Common Mistakes:**\n- Not listening for `drain` when using manual writes.\n- Calling `resume()` before `drain` causing memory blow.\n- Ignoring `pipe()` return value (it returns destination for chaining).\n\n**Real-world Example:**\nReading a large file and compressing (zlib) then writing to disk: compression may be slow, so `gzip` stream applies backpressure to `fs.createReadStream`.\n\n**Advanced Notes:**\n`readable.read()` with manual control. `readable.isPaused()`. `writable.writableHighWaterMark`. `writable.writableLength` current buffer size. Backpressure can be monitored with `stream.on('drain')` and `'pause'` events. Node.js 15+ `stream\u002Fpromises` pipeline returns promise. `pipeline` also cleans up streams on errors.",[353,352,287,354],{"id":471,"category":472,"question":473,"answer":474,"level":376,"tags":475},58,"Security Patterns","What are common JavaScript security vulnerabilities (XSS, CSRF, prototype pollution)? How to prevent them in production apps?","**Concept Explanation:**\n- XSS (Cross-site Scripting): injecting malicious scripts via unsanitized user input.\n- CSRF (Cross-site Request Forgery): tricking user into making unauthorized requests.\n- Prototype pollution: modifying `Object.prototype` to inject properties causing unexpected behavior.\nPrevention: sanitize output (escape\u002Fencode), Content Security Policy, use `Object.freeze(Object.prototype)`, CSRF tokens, and avoid unsafe patterns.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F XSS vulnerable\nconst userInput = '\u003Cimg src=x onerror=alert(1)>';\nelement.innerHTML = userInput; \u002F\u002F executes script\n\n\u002F\u002F XSS safe\nelement.textContent = userInput; \u002F\u002F escapes HTML\n\u002F\u002F or\nconst sanitized = userInput.replace(\u002F[\u003C>&]\u002Fg, (c) => ({'\u003C':'&lt;','>':'&gt;','&':'&amp;'})[c]);\n\n\u002F\u002F Prototype pollution vulnerable\nconst merge = (target, source) => {\n  for (let key in source) target[key] = source[key];\n};\nconst payload = '{\"__proto__\":{\"isAdmin\":true}}';\nmerge({}, JSON.parse(payload)); \u002F\u002F pollutes Object.prototype\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F XSS prevention in React\n\u002F\u002F React escapes by default\nconst userInput = '\u003Cimg onerror=alert(1) src=x>';\nreturn \u003Cdiv>{userInput}\u003C\u002Fdiv>; \u002F\u002F safe (renders as string)\n\n\u002F\u002F But dangerouslySetInnerHTML is unsafe\n\u003Cdiv dangerouslySetInnerHTML={{__html: userInput}} \u002F> \u002F\u002F XSS risk\n\n\u002F\u002F CSP header (helmet in Express)\nconst helmet = require('helmet');\napp.use(helmet.contentSecurityPolicy({\n  directives: {\n    defaultSrc: [\"'self'\"],\n    scriptSrc: [\"'self'\", 'trusted-cdn.com'],\n  }\n}));\n\n\u002F\u002F Prototype pollution prevention\n\u002F\u002F 1. Freeze prototype\nObject.freeze(Object.prototype);\nObject.freeze(Object.getPrototypeOf({}));\n\n\u002F\u002F 2. Use Map instead of plain objects for dynamic keys\nconst map = new Map();\nmap.set('__proto__', 'value'); \u002F\u002F safe\n\n\u002F\u002F 3. Validate before merging\nfunction safeMerge(target, source) {\n  if (source && source.__proto__) delete source.__proto__;\n  \u002F\u002F also check constructor\n  return Object.assign(target, source);\n}\n\n\u002F\u002F CSRF prevention\n\u002F\u002F Express with csurf middleware\nconst csrf = require('csurf');\napp.use(csrf());\napp.get('\u002Fform', (req, res) => {\n  res.send(`\u003Cinput type=\"hidden\" name=\"_csrf\" value=\"${req.csrfToken()}\">`);\n});\n\u002F\u002F SameSite cookies\napp.use(require('cookie-session')({\n  sameSite: 'strict',\n  secure: true\n}));\n```\n\n**Practical Usage:**\n- Always escape output (never trust user input).\n- Use CSP headers to restrict script sources.\n- Validate and sanitize input (JSON schema, DOMPurify for HTML).\n- Set `SameSite=Strict` or `Lax` for cookies.\n- Use `Object.create(null)` for dictionaries.\n\n**Interview Insight:**\nXSS is the most common web vulnerability; sanitizing on output (not input) is correct. Prototype pollution often comes from unsafe `merge` or `clone` operations. `JSON.parse` with reviver can check for `__proto__`. CSRF can be mitigated with tokens, double-submit cookies, or SameSite attributes.\n\n**Common Mistakes:**\n- Blacklisting sanitization (bypass possible).\n- Storing sensitive data in localStorage (accessible via XSS).\n- Using `eval` or `new Function` with user input.\n- Forgetting CSP for inline scripts (use `nonce`).\n\n**Real-world Example:**\nLodash's `_.merge` had prototype pollution vulnerability (CVE-2019-10744). Fixed by not processing `__proto__`. Many npm packages have had similar issues.\n\n**Advanced Notes:**\nContent Security Policy can report violations via `report-uri`. Trusted Types (modern browsers) enforce sanitization. Subresource Integrity (SRI) for CDN scripts. DOMPurify library is industry standard for HTML sanitization. Node.js `vm2` for sandboxing. `helmet` provides secure headers.",[476,477,478,479,480],"security","xss","csrf","prototype-pollution","csp",{"id":482,"category":483,"question":484,"answer":485,"level":376,"tags":486},59,"Production Scaling","How do you architect a production-grade Node.js application? Discuss error handling, logging, monitoring, and graceful shutdown.","**Concept Explanation:**\nProduction Node.js architecture includes: process management (PM2, cluster), structured logging (winston, pino), centralized error handling, health checks, monitoring (Prometheus, Datadog), graceful shutdown (SIGTERM handling), and environment configuration (12-factor app). Use async\u002Fawait with try\u002Fcatch, uncaught exception handlers, and externalize state (Redis, database).\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Graceful shutdown\nprocess.on('SIGTERM', async () => {\n  console.log('SIGTERM received, closing server');\n  await server.close(); \u002F\u002F stop accepting new connections\n  await db.disconnect();\n  process.exit(0);\n});\n\n\u002F\u002F Uncaught exception handler\nprocess.on('uncaughtException', (err) => {\n  console.error('Uncaught Exception:', err);\n  process.exit(1); \u002F\u002F crash and restart via orchestrator\n});\n\n\u002F\u002F Unhandled rejection\nprocess.on('unhandledRejection', (reason, promise) => {\n  console.error('Unhandled Rejection:', reason);\n});\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Structured logging (pino)\nconst pino = require('pino');\nconst logger = pino({ level: process.env.LOG_LEVEL || 'info' });\nlogger.info({ userId: 123, action: 'login' }, 'User logged in');\n\n\u002F\u002F Express error handling middleware\napp.use((err, req, res, next) => {\n  logger.error({ err, reqId: req.id }, err.message);\n  if (err.isOperational) {\n    res.status(err.statusCode).json({ error: err.message });\n  } else {\n    res.status(500).json({ error: 'Internal Server Error' });\n  }\n});\n\n\u002F\u002F Health check endpoint\napp.get('\u002Fhealth', (req, res) => {\n  const checks = [checkDatabase(), checkRedis()];\n  Promise.all(checks).then(() => res.status(200).send('OK'))\n    .catch(() => res.status(503).send('Unhealthy'));\n});\n\n\u002F\u002F Environment configuration (dotenv + schema validation)\nconst env = require('env-var');\nconst PORT = env.get('PORT').default(3000).asPortNumber();\nconst DB_URL = env.get('DATABASE_URL').required().asString();\n\n\u002F\u002F PM2 ecosystem.config.js\nmodule.exports = {\n  apps: [{\n    name: 'app',\n    script: 'server.js',\n    instances: 'max',\n    exec_mode: 'cluster',\n    max_memory_restart: '1G',\n    error_file: 'logs\u002Ferr.log',\n    out_file: 'logs\u002Fout.log',\n    time: true\n  }]\n};\n```\n\n**Practical Usage:**\n- Use process manager (PM2, systemd) for auto-restart and logging.\n- Implement readiness\u002Fliveness probes for Kubernetes.\n- Use APM tools (New Relic, DataDog) for performance.\n- Store secrets in environment variables or vault (never in code).\n\n**Interview Insight:**\nDistinguish between operational errors (expected, handled gracefully) and programmer errors (crash and restart). Use `SIGTERM` for graceful shutdown (give time for in-flight requests). Implement distributed tracing for microservices. Use circuit breakers for external calls.\n\n**Common Mistakes:**\n- Not handling `SIGTERM` (default kill after 30s).\n- Logging sensitive data (passwords, tokens).\n- Synchronous operations in event loop (blocks shutdown).\n- Not using `npm shrinkwrap` or lockfiles.\n\n**Real-world Example:**\nUber's Node.js stack uses similar patterns with custom metrics and health checks; Netflix uses Hystrix for resilience.\n\n**Advanced Notes:**\n`node --abort-on-uncaught-exception` for core dumps. `node --trace-warnings`. Use `async_hooks` for request context propagation. OpenTelemetry for observability. Chaos engineering: randomly kill processes to test resilience. Rate limiting and load shedding (express-rate-limit).",[487,488,106,489,490],"production","scaling","logging","graceful-shutdown",{"id":492,"category":493,"question":494,"answer":495,"level":376,"tags":496},60,"Design Patterns","Explain advanced JavaScript design patterns: Module, Singleton, Factory, Observer, and their modern ES6+ implementations.","**Concept Explanation:**\nDesign patterns are reusable solutions. Module pattern encapsulates private data using closures (ES6 modules are native). Singleton ensures single instance (use ES6 module caching). Factory creates objects without specifying exact class (useful for DI). Observer (pub-sub) for event handling. Modern patterns use classes, modules, WeakMaps, and proxies.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Module pattern (revealing)\nconst counterModule = (() => {\n  let count = 0;\n  const increment = () => ++count;\n  const getCount = () => count;\n  return { increment, getCount };\n})();\n\n\u002F\u002F ES6 Module (native)\n\u002F\u002F counter.js\nexport let count = 0;\nexport const increment = () => ++count;\n\n\u002F\u002F Singleton (ES6 module cached)\n\u002F\u002F db.js\nclass Database { constructor() { this.connection = 'pool'; } }\nexport default new Database(); \u002F\u002F single instance\n\n\u002F\u002F Factory pattern\nclass User { constructor(type, name) { this.type = type; this.name = name; } }\nclass Admin extends User {}\nclass Guest extends User {}\nclass UserFactory {\n  static create(type, name) {\n    switch(type) {\n      case 'admin': return new Admin('admin', name);\n      case 'guest': return new Guest('guest', name);\n      default: return new User('regular', name);\n    }\n  }\n}\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Observer pattern (EventEmitter)\nclass EventEmitter {\n  constructor() {\n    this.events = new Map();\n  }\n  on(event, listener) {\n    if (!this.events.has(event)) this.events.set(event, []);\n    this.events.get(event).push(listener);\n  }\n  emit(event, ...args) {\n    const listeners = this.events.get(event);\n    if (listeners) listeners.forEach(fn => fn(...args));\n  }\n  off(event, listener) {\n    const listeners = this.events.get(event);\n    if (listeners) {\n      const idx = listeners.indexOf(listener);\n      if (idx > -1) listeners.splice(idx, 1);\n    }\n  }\n}\nconst emitter = new EventEmitter();\nemitter.on('data', (msg) => console.log(msg));\nemitter.emit('data', 'Hello');\n\n\u002F\u002F Using Node's built-in EventEmitter\nconst EventEmitter = require('events');\nclass MyEmitter extends EventEmitter {}\n\n\u002F\u002F Dependency Injection pattern\nclass Logger { log(msg) { console.log(msg); } }\nclass UserService {\n  constructor(logger) {\n    this.logger = logger;\n  }\n  createUser(name) {\n    this.logger.log(`Creating user ${name}`);\n  }\n}\nconst logger = new Logger();\nconst userService = new UserService(logger);\n\n\u002F\u002F Strategy pattern\nconst strategies = {\n  fast: (data) => data.sort(),\n  slow: (data) => data.sort((a,b) => { \u002F* complex *\u002F })\n};\nfunction process(strategy, data) {\n  return strategies[strategy](data);\n}\n```\n\n**Practical Usage:**\n- Module: code organization (already via ES modules).\n- Singleton: database connection pools, configuration managers.\n- Factory: creating domain objects based on configuration.\n- Observer: event handling, reactive programming.\n\n**Interview Insight:**\nES6 modules replace revealing module pattern but are static (cannot be created at runtime). Singleton in JS is natural due to module caching. Observer is foundation of Node.js event system. Modern frameworks use many patterns (React uses HOC, render props, hooks).\n\n**Common Mistakes:**\n- Overusing Singleton (makes testing hard).\n- Not unsubscribing from observers (memory leaks).\n- Tight coupling in Factory (can be solved by DI).\n\n**Real-world Example:**\nRedux uses Observer pattern (store subscription). Express uses middleware pattern (chain of responsibility). Mongoose uses Singleton for connection.\n\n**Advanced Notes:**\nProxy pattern can intercept property access. Decorator pattern (experimental in JS, native in TypeScript). Command pattern for undo\u002Fredo. Publish-subscribe is similar to Observer but decoupled via a broker. Modern patterns include Flux (unidirectional data flow).",[497,498,499,500,501],"design-patterns","module","singleton","factory","observer",{"id":503,"category":245,"question":504,"answer":505,"level":376,"tags":506},61,"What are critical rendering path optimizations? How do you reduce layout shifts and improve Core Web Vitals (LCP, FID, CLS)?","**Concept Explanation:**\nCritical Rendering Path (CRP) is the sequence of steps (DOM, CSSOM, render tree, layout, paint) to display content. Core Web Vitals: Largest Contentful Paint (LCP – loading), First Input Delay (FID – interactivity), Cumulative Layout Shift (CLS – visual stability). Optimizations: preload critical resources, minimize CSS blocking, async\u002Fdefer scripts, optimize images, set dimensions for media, and avoid inserting content above existing content.\n\n**Syntax Explanation:**\n```html\n\u003C!-- Preload critical assets -->\n\u003Clink rel=\"preload\" href=\"critical.css\" as=\"style\">\n\u003Clink rel=\"preload\" href=\"hero-image.webp\" as=\"image\">\n\n\u003C!-- Defer non-critical scripts -->\n\u003Cscript src=\"analytics.js\" defer>\u003C\u002Fscript>\n\u003Cscript src=\"non-critical.js\" async>\u003C\u002Fscript>\n\n\u003C!-- Set explicit dimensions -->\n\u003Cimg src=\"image.jpg\" width=\"800\" height=\"600\" alt=\"description\">\n\n\u003C!-- CSS in critical path -->\n\u003Cstyle> \u002F* inline critical CSS for above-the-fold *\u002F \u003C\u002Fstyle>\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Lazy loading images with IntersectionObserver\nconst observer = new IntersectionObserver((entries) => {\n  entries.forEach(entry => {\n    if (entry.isIntersecting) {\n      const img = entry.target;\n      img.src = img.dataset.src;\n      observer.unobserve(img);\n    }\n  });\n});\ndocument.querySelectorAll('img[data-src]').forEach(img => observer.observe(img));\n\n\u002F\u002F Preconnect to origins\n\u003Clink rel=\"preconnect\" href=\"https:\u002F\u002Fapi.example.com\">\n\n\u002F\u002F Reducing CLS: reserve space for dynamic content\n\u003Cdiv style=\"min-height: 200px;\">\n  \u003C!-- async loaded content -->\n\u003C\u002Fdiv>\n\n\u002F\u002F Font loading with font-display\n@font-face {\n  font-family: 'CustomFont';\n  src: url('font.woff2');\n  font-display: swap; \u002F* avoids invisible text *\u002F\n}\n\n\u002F\u002F Measuring Web Vitals (web-vitals library)\nimport {getLCP, getFID, getCLS} from 'web-vitals';\ngetLCP(console.log);\ngetFID(console.log);\ngetCLS(console.log);\n```\n\n**Practical Usage:**\n- Inline critical CSS (under 14KB) and defer non-critical.\n- Use `loading=\"lazy\"` for images\u002Fiframes.\n- Optimize server response (TTFB, CDN, caching).\n- Reduce JavaScript bundle size (code splitting, tree shaking).\n\n**Interview Insight:**\nLCP largest element (image or block text) should load quickly. FID measures responsiveness; break long tasks into smaller chunks. CLS calculates unexpected layout shifts; avoid inserting content above existing content without user interaction. Use `transform` for animations (doesn't trigger layout).\n\n**Common Mistakes:**\n- Not setting width\u002Fheight on images causing shifts.\n- Loading fonts with `font-display: block` causing invisible text.\n- Injecting ads or banners dynamically without reserved space.\n\n**Real-world Example:**\nE-commerce product page: LCP is product image (preload hero image). FID improved by deferring analytics scripts. CLS avoided by setting fixed aspect ratio on carousel.\n\n**Advanced Notes:**\n`\u003Clink rel=\"preload\">` as high priority; `prefetch` for next navigation. `workbox` for service worker caching. `requestIdleCallback` for non-critical work. React 18's `useTransition` for non-urgent updates. Lighthouse and PageSpeed Insights for auditing.",[507,242,508,509,510],"core-web-vitals","critical-rendering-path","lcp","cls",{"id":512,"category":513,"question":514,"answer":515,"level":376,"tags":516},62,"Architecture","How do you implement a reactive system using Proxies (similar to Vue 3)? Explain dependency tracking and effect scheduling.","**Concept Explanation:**\nReactive system tracks data dependencies and automatically updates effects when data changes. Using Proxy, we intercept get (track) and set (trigger) operations. A reactive variable has a dependency map; when get called, the current active effect is recorded. When set called, all dependent effects are re-run, scheduled via microtask or queue.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Basic reactive (Vue 3 style)\nconst data = reactive({ count: 0, text: 'hello' });\neffect(() => {\n  console.log(`Count is ${data.count}`);\n});\ndata.count++; \u002F\u002F triggers effect re-run\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Complete mini reactive system\nlet activeEffect = null;\nconst targetMap = new WeakMap(); \u002F\u002F target -> Map(key -> Set(effects))\n\nfunction track(target, key) {\n  if (!activeEffect) return;\n  let depsMap = targetMap.get(target);\n  if (!depsMap) targetMap.set(target, (depsMap = new Map()));\n  let dep = depsMap.get(key);\n  if (!dep) depsMap.set(key, (dep = new Set()));\n  dep.add(activeEffect);\n}\n\nfunction trigger(target, key) {\n  const depsMap = targetMap.get(target);\n  if (!depsMap) return;\n  const dep = depsMap.get(key);\n  if (dep) dep.forEach(effect => effect.scheduler ? effect.scheduler() : effect());\n}\n\nfunction reactive(target) {\n  return new Proxy(target, {\n    get(obj, key) {\n      track(obj, key);\n      return Reflect.get(obj, key);\n    },\n    set(obj, key, value) {\n      const result = Reflect.set(obj, key, value);\n      trigger(obj, key);\n      return result;\n    }\n  });\n}\n\nfunction effect(fn, options = {}) {\n  const effectFn = () => {\n    try {\n      activeEffect = effectFn;\n      return fn();\n    } finally {\n      activeEffect = null;\n    }\n  };\n  effectFn.scheduler = options.scheduler;\n  effectFn();\n  return effectFn;\n}\n\n\u002F\u002F Scheduling with microtask (batching updates)\nlet queued = false;\nconst pendingEffects = new Set();\nfunction queueEffect(effectFn) {\n  pendingEffects.add(effectFn);\n  if (!queued) {\n    queued = true;\n    queueMicrotask(() => {\n      pendingEffects.forEach(fn => fn());\n      pendingEffects.clear();\n      queued = false;\n    });\n  }\n}\n\n\u002F\u002F Usage\nconst state = reactive({ count: 0 });\neffect(() => {\n  console.log(`Count changed to ${state.count}`);\n});\nstate.count = 1; \u002F\u002F logs once (batch)\nstate.count = 2; \u002F\u002F logs once\n\n\u002F\u002F Computed values\nfunction computed(getter) {\n  let dirty = true;\n  let value;\n  const effectFn = effect(getter, {\n    scheduler: () => {\n      dirty = true;\n      trigger(computedObj, 'value');\n    }\n  });\n  const computedObj = {\n    get value() {\n      if (dirty) {\n        value = effectFn();\n        dirty = false;\n      }\n      track(computedObj, 'value');\n      return value;\n    }\n  };\n  return computedObj;\n}\n```\n\n**Practical Usage:**\n- Reactive UI frameworks (Vue, MobX).\n- State management libraries.\n- Data binding in non-framework applications.\n\n**Interview Insight:**\nVue 3's reactivity uses Proxies for better performance and detection of property addition\u002Fdeletion. Dependency tracking is based on effect stacks. `effect` runs synchronously, but scheduling can batch updates. WeakMap prevents memory leaks (targets can be GCed).\n\n**Common Mistakes:**\n- Forgetting to handle nested reactivity (reactive objects inside).\n- Not cleaning up effects (memory leaks in long-lived apps).\n- Triggering effects synchronously causing infinite loops.\n\n**Real-world Example:**\nVue 3 composition API's `ref` and `reactive` are implemented similarly. MobX uses `@observable` decorators that compile to Proxy or legacy defineProperty.\n\n**Advanced Notes:**\nVue 3 also has `readonly`, `shallowReactive`, `shallowRef`. Effect `stop` function to dispose. `ref` for primitives wraps in object. Vue's reactivity also handles collections (Map, Set). Vue 3 uses `effectScope` for grouping effects.",[517,417,518,519],"reactivity","vue","dependency-tracking",{"id":521,"category":522,"question":523,"answer":524,"level":376,"tags":525},63,"Modern APIs","What are the Temporal API and other modern JavaScript proposals (Records\u002FTuples, Decorators, Pipeline operator)? Explain how they improve the language.","**Concept Explanation:**\nTemporal API provides a modern, immutable date\u002Ftime library (replacing `Date`). Records and Tuples are deeply immutable, structural value types. Decorators add meta-programming for classes\u002Fmethods (similar to Python\u002FJava). Pipeline operator (`|>`) improves function composition readability. These proposals (ES2025+) aim to reduce boilerplate and bugs.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Temporal (stage 3)\nconst now = Temporal.Now.instant();\nconst date = Temporal.PlainDate.from('2025-01-01');\nconst result = date.add({ days: 5 });\nconsole.log(result.toString()); \u002F\u002F '2025-01-06'\n\n\u002F\u002F Records and Tuples (stage 2) – deep immutable\nconst point = #{ x: 1, y: 2 }; \u002F\u002F record\nconst colors = #[ 'red', 'green', 'blue' ]; \u002F\u002F tuple\nconst newPoint = #{ ...point, y: 3 }; \u002F\u002F new record\n\n\u002F\u002F Decorators (stage 3)\nclass User {\n  @logged\n  @bound\n  getName() { return this.name; }\n}\n\n\u002F\u002F Pipeline operator (stage 2)\nconst result = \"hello\"\n  |> doubleSay\n  |> capitalize\n  |> exclaim;\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Temporal – date arithmetic\nconst birthday = Temporal.PlainDate.from('1990-05-15');\nconst today = Temporal.Now.plainDateISO();\nconst age = today.since(birthday, { largestUnit: 'year' });\nconsole.log(age.years); \u002F\u002F approximate years\n\n\u002F\u002F Temporal – time zones\nconst meeting = Temporal.ZonedDateTime.from('2025-06-01T10:00:00[America\u002FNew_York]');\nconst london = meeting.withTimeZone('Europe\u002FLondon');\nconsole.log(london.toString());\n\n\u002F\u002F Records – equality by value (not reference)\nconst rec1 = #{ a: 1, b: 2 };\nconst rec2 = #{ a: 1, b: 2 };\nconsole.log(rec1 === rec2); \u002F\u002F true (deep structural equality)\n\n\u002F\u002F Tuple methods\nconst numbers = #[1, 2, 3];\nconst doubled = numbers.map(x => x * 2); \u002F\u002F returns new tuple\n\n\u002F\u002F Decorators: validation\nexport function validate(min, max) {\n  return function(target, context) {\n    return function(value) {\n      if (value \u003C min || value > max) throw new Error('Invalid');\n      return value;\n    };\n  };\n}\nclass Temperature {\n  @validate(-273, 1000)\n  accessor kelvin = 0;\n}\n\n\u002F\u002F Pipeline with placeholder (Hack style)\nconst result = numbers\n  |> filter(%, x => x > 2)\n  |> map(%, x => x * 2);\n```\n\n**Practical Usage:**\n- Temporal replaces moment.js with immutable, timezone-aware APIs.\n- Records\u002FTuples improve performance (immutable structures), useful in Redux.\n- Decorators for logging, validation, dependency injection.\n- Pipeline operator for chaining transformations without nesting.\n\n**Interview Insight:**\nTemporal solves Date problems: mutability, weird API, timezone handling. Records\u002FTuples are deeply immutable and compared by value, enabling faster reconciliation in UI frameworks. Decorators currently in stage 3 (available in TypeScript 5.0+). Pipeline operator has multiple proposals (F# vs Hack style).\n\n**Common Mistakes:**\n- Assuming Temporal is widely supported (use polyfill).\n- Expecting Records to be mutable (they are not).\n- Overusing decorators (can make code hard to trace).\n\n**Real-world Example:**\nRedux reducer with Records: `#{ ...state, items: #[...state.items, newItem] }` ensures immutability.\n\n**Advanced Notes:**\nTemporal has types: Instant, PlainDate, PlainTime, PlainDateTime, ZonedDateTime, Duration, etc. Record\u002FTuple cannot contain objects (only primitives or other records\u002Ftuples). Decorator metadata API (stage 3) enables reflection. Pipeline operator can be implemented via Babel plugin. Other proposals: Pattern Matching, `using` declarations, `Array.fromAsync`.",[526,527,528,529,530,531],"temporal","records","tuples","decorators","pipeline","es2025",{"id":533,"category":534,"question":535,"answer":536,"level":376,"tags":537},64,"Rendering & Compositing","Explain compositing layers in the browser and how to use will-change, transform, and opacity for GPU acceleration.","**Concept Explanation:**\nBrowsers create compositing layers for elements with certain CSS properties (3D transforms, `will-change`, `opacity` animations). Layers are painted independently and composited by GPU, avoiding reflows and repaints for the rest of the page. Use `transform` (translation, scale, rotation) and `opacity` for animations as they only trigger compositing (not layout or paint). `will-change` hints upcoming changes, but overuse can create too many layers (memory overhead).\n\n**Syntax Explanation:**\n```css\n\u002F* GPU-accelerated animation *\u002F\n.box {\n  will-change: transform;\n  transition: transform 0.3s ease;\n}\n.box:hover {\n  transform: translateX(100px);\n}\n\n\u002F* Opacity only composite *\u002F\n.fade {\n  will-change: opacity;\n  transition: opacity 0.2s;\n}\n.fade.hide {\n  opacity: 0;\n}\n\n\u002F* Creating a new layer *\u002F\n.layer {\n  transform: translateZ(0); \u002F* old trick *\u002F\n  backface-visibility: hidden; \u002F* also creates layer *\u002F\n}\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F JavaScript scroll handler with transform (cheap)\nlet scrollY = 0;\nwindow.addEventListener('scroll', () => {\n  scrollY = window.scrollY;\n  element.style.transform = `translateY(${scrollY * 0.5}px)`;\n});\n\n\u002F\u002F Detecting layers in DevTools\n\u002F\u002F Chrome: More tools -> Layers, or Layers panel in Performance\n\n\u002F\u002F Bad: animating top\u002Fleft (causes layout)\nfunction badAnimation() {\n  let pos = 0;\n  setInterval(() => {\n    element.style.top = pos + 'px'; \u002F\u002F triggers layout\n    pos++;\n  }, 16);\n}\n\n\u002F\u002F Good: animating transform\nfunction goodAnimation() {\n  let pos = 0;\n  setInterval(() => {\n    element.style.transform = `translateX(${pos}px)`; \u002F\u002F composite only\n    pos++;\n  }, 16);\n}\n\n\u002F\u002F Using requestAnimationFrame for smoothness\nlet start;\nfunction animate(timestamp) {\n  if (!start) start = timestamp;\n  const progress = (timestamp - start) \u002F 1000;\n  element.style.transform = `translateX(${Math.min(progress * 200, 200)}px)`;\n  if (progress \u003C 1) requestAnimationFrame(animate);\n}\nrequestAnimationFrame(animate);\n```\n\n**Practical Usage:**\n- Animate `transform` and `opacity` only.\n- Use `will-change` for elements that will animate (don't overuse).\n- Limit layer count (each layer uses memory).\n- Avoid `position: fixed` in scroll containers (creates new layer but costly).\n\n**Interview Insight:**\nCompositing layers are managed by the browser's compositor thread. `transform` and `opacity` are cheap because they can be handled by GPU without main thread involvement (except for starting the animation). `will-change` should be applied just before animation and removed after; permanent `will-change` wastes memory.\n\n**Common Mistakes:**\n- Applying `will-change` to many elements (layer explosion).\n- Animating `width`, `height`, `top`, `left` causing repaints.\n- Using `transform: translateZ(0)` on every element.\n\n**Real-world Example:**\nParallax scrolling: use `transform: translateY()` on background layers, keeping them in separate layers for smooth performance.\n\n**Advanced Notes:**\n`contain` CSS property can hint at isolation. `content-visibility: auto` skips rendering of off-screen content. Layers can be inspected via Chrome `chrome:\u002F\u002Fflags\u002F#composited-layer-borders`. The compositor thread also handles scroll and pinch-zoom. WebGL\u002FCanvas also use GPU. Video elements are separate layers. `will-change: transform, opacity` combines hints.",[538,539,540,242,541],"compositing","gpu","animation","will-change",{"id":543,"category":219,"question":544,"answer":545,"level":376,"tags":546},65,"Explain how JavaScript engines optimize array operations: packed vs holey arrays, SMI vs double elements, and array methods performance.","**Concept Explanation:**\nV8 categorizes arrays by elements kind: packed (no holes) vs holey (missing indices), and element types: SMI (small integers), double (floating point), and tagged (generic). Optimizations apply to packed SMI arrays (fastest). Holey arrays require prototype chain checks. Methods like `map`\u002F`filter` are optimized for packed arrays but slower for holey due to missing element checks.\n\n**Syntax Explanation:**\n```javascript\n\u002F\u002F Packed SMI (most optimized)\nconst arr1 = [1, 2, 3]; \u002F\u002F PACKED_SMI_ELEMENTS\n\n\u002F\u002F Packed double\nconst arr2 = [1.1, 2.2, 3.3]; \u002F\u002F PACKED_DOUBLE_ELEMENTS\n\n\u002F\u002F Packed tagged (mixed types)\nconst arr3 = [1, 'a', {}]; \u002F\u002F PACKED_ELEMENTS\n\n\u002F\u002F Holey (with missing index)\nconst arr4 = [1, , 3]; \u002F\u002F HOLEY_SMI_ELEMENTS\narr4[10] = 5; \u002F\u002F becomes holey\n```\n\n**Code Examples:**\n```javascript\n\u002F\u002F Performance differences\nconst packed = [1,2,3,4,5];\nconst holey = [1,2,3,4,5];\ndelete holey[2]; \u002F\u002F creates hole\n\nconsole.time('packed forEach');\npacked.forEach(v => {});\nconsole.timeEnd('packed forEach');\n\nconsole.time('holey forEach');\nholey.forEach(v => {}); \u002F\u002F slower due to hole checks\nconsole.timeEnd('holey forEach');\n\n\u002F\u002F Avoid creating holes\n\u002F\u002F Bad: const arr = [1,2,3]; arr[5] = 10;\n\u002F\u002F Good: arr.push(10);\n\n\u002F\u002F Preallocate with correct size\nconst len = 1000000;\nconst arr = new Array(len); \u002F\u002F holey, not recommended\nfor (let i = 0; i \u003C len; i++) arr[i] = i; \u002F\u002F becomes packed after fill\n\n\u002F\u002F Better: use Array.from or fill\nconst arr2 = Array.from({ length: len }, (_, i) => i); \u002F\u002F packed\n\n\u002F\u002F Array methods performance\n\u002F\u002F map with callback vs manual loop (often similar with JIT)\nconst result = packed.map(x => x * 2); \u002F\u002F good, optimized\n\n\u002F\u002F Avoid changing array kind after creation\nconst arr5 = [1,2,3]; \u002F\u002F PACKED_SMI\narr5.push(4.5); \u002F\u002F transitions to PACKED_DOUBLE\narr5.push('x'); \u002F\u002F transitions to PACKED_ELEMENTS (slower)\n\n\u002F\u002F For dictionaries, use Map over object with numeric keys\nconst map = new Map(); \u002F\u002F better for dynamic keys\n```\n\n**Practical Usage:**\n- Initialize arrays with all elements (avoid `new Array(length)`).\n- Don't create holes (using `delete` or sparse assignments).\n- Keep element types consistent (avoid mixing numbers with strings).\n- Use typed arrays (`Uint8Array`) for numeric data.\n\n**Interview Insight:**\nElements kind transitions are one-way: PACKED_SMI -> PACKED_DOUBLE -> PACKED_ELEMENTS -> to holey variants. Holey variants require prototype checks for missing elements (slower). `Array.from` and spread produce packed arrays. `arr.length = 0` preserves elements kind (if you add same type).\n\n**Common Mistakes:**\n- Using `new Array(1000)` creating holey array, then filling one by one.\n- Deleting array elements (use `arr[index] = undefined` instead).\n- Mixing types in performance-critical loops.\n\n**Real-world Example:**\nData processing pipelines (e.g., particle systems) benefit from typed arrays. Game loops should use packed SMI arrays for coordinates.\n\n**Advanced Notes:**\n`%DebugPrint(arr)` in V8 to see elements kind. `array.flat()` creates holey arrays? Implementation varies. `for...of` has different performance characteristics than indexed `for` loop. `Array.prototype.sort` is optimized for SMI\u002Fdouble. Modern JIT can sometimes optimize holey access but not as much as packed. Wasm arrays have no element kind overhead.",[62,378,242,547,251],"elements-kind",1779734543421]