Mastery Vault

Accessing Level 99 Full Stack Intelligence

JavaScript Core + Advanced

JS_01

1. What is Event-Driven Architecture?

A design pattern where system flow is determined by events like user actions, sensor outputs, or messages from other programs. It uses an event loop to handle these triggers asynchronously without blocking the main execution thread.

System Detail & Playground
Real-Time Use: Used in Node.js servers to handle thousands of concurrent connections efficiently, and in browser UIs to react to user clicks without freezing the screen.
console.log("System Initialized..."); setTimeout(() => { console.log("Event Triggered: User Clicked Login"); }, 1000); console.log("Waiting for events...");
SYSTEM_OUTPUT:
JS_02

2. What is Event Bubbling and Capturing?

Bubbling triggers events from the target element up to the root, while capturing flows from the root down to the target. These phases allow developers to manage nested interactions and implement event delegation patterns.

System Detail & Playground
Real-Time Use: Essential for "Event Delegation" where you attach one listener to a parent menu instead of 100 listeners to individual menu items, saving memory.
console.log("Phase 1: Capturing (Root -> Target)"); console.log("Phase 2: Target (Executing Logic)"); console.log("Phase 3: Bubbling (Target -> Root)"); console.log("Delegation active: Parent handled child event.");
SYSTEM_OUTPUT:
JS_03

3. How does the JavaScript event loop work?

The event loop is a constant process that monitors the call stack and the task queue. If the stack is empty, it takes the first task from the queue and pushes it onto the stack, enabling non-blocking I/O operations.

System Detail & Playground
Real-Time Use: Prevents "UI Blocking" during heavy data processing. Chrome uses this to keep animations smooth while fetching API data in the background.
console.log("Step 1: Script Start"); setTimeout(() => console.log("Step 3: Macrotask (Loop Cycle 2)"), 0); Promise.resolve().then(() => console.log("Step 2: Microtask (Loop Cycle 1)")); console.log("Step 1: Script End");
SYSTEM_OUTPUT:
JS_05

5. What is hoisting?

Hoisting is a behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase. This allows functions to be used before they are formally defined in the code.

System Detail & Playground
Real-Time Use: Used in library development to organize utility functions at the bottom of a file while keeping the core logic clean and readable at the top.
console.log("Hoisted Var:", myVar); // undefined var myVar = "Loaded"; sayHello(); // Works due to function hoisting function sayHello() { console.log("System: Hello from the bottom!"); }
SYSTEM_OUTPUT:
JS_08

8. What are closures?

A closure is a function that remembers its outer scope even after that scope has finished executing. It provides a way to create private variables and maintain state across multiple function calls.

System Detail & Playground
Real-Time Use: Critical for data privacy (Encapsulation) in JS. Used in React hooks like `useState` to remember values between component re-renders.
function createVault() { let balance = 0; return (amount) => { balance += amount; return "Vault Balance: $" + balance; }; } const myVault = createVault(); console.log(myVault(100)); console.log(myVault(50));
SYSTEM_OUTPUT:
JS_04

4. What are microtasks and macrotasks?

Microtasks (like Promises) have higher priority and execute immediately after the current script, while macrotasks (like setTimeout) wait for the next event loop check. This distinction ensures that critical asynchronous logic runs before the browser performs rendering or handles user input.

System Detail & Playground
Real-Time Use: Ensuring UI state updates (Promises) happen before the browser attempts to repaint the screen, avoiding visual flickering.
console.log("1. Start"); setTimeout(() => console.log("4. Macrotask (setTimeout)"), 0); Promise.resolve().then(() => console.log("3. Microtask (Promise)")); console.log("2. End");
SYSTEM_OUTPUT:
JS_06

6. What is the Global Execution Context?

The base environment where any JavaScript code starts its execution, creating the global object (window in browsers) and the 'this' keyword. It sets up the memory heap and call stack before any specific functions are called.

System Detail & Playground
Real-Time Use: Managing application-wide constants and global state that need to be accessible from any part of the file without explicit passing.
console.log("Global context active."); console.log("Window object defined:", typeof window !== 'undefined'); var globalId = "SYS_99"; console.log("Available in context:", globalId);
SYSTEM_OUTPUT:
JS_07

7. What is lexical scope?

Lexical scope means that the accessibility of variables is determined by their physical location within the source code during the nesting phase. An inner function always has access to the variables defined in its outer physical parent scope.

System Detail & Playground
Real-Time Use: Heavily used in functional programming and React component patterns to share state between nested helper functions without global variables.
const outer = "Outer Power"; function checkScope() { const inner = "Inner Energy"; console.log("Accessing:", outer); // Lexical access console.log("Accessing:", inner); } checkScope();
SYSTEM_OUTPUT:
JS_09

9. What are closure pitfalls inside loops?

When using 'var' inside loops, closures capture the same variable reference, often leading to all iterations sharing the final loop value. Using 'let' fixes this by creating a unique block-level binding for every single iteration of the loop.

System Detail & Playground
Real-Time Use: A classic bug in older JS code where clicking multiple buttons would always show the same ID. Solved by modern block-scoping (`let`).
console.log("Testing Loop with 'var' (Buggy):"); for (var i = 1; i <= 3; i++) { setTimeout(() => console.log("Var Output:", i), 100); } // Fix with let after delay...
SYSTEM_OUTPUT:
JS_10

10. var, let, and const differences?

'var' is function-scoped and hoisted, 'let' is block-scoped and non-reassignable if using 'const'. Modern development prioritizes 'const' for stability and 'let' only when value reassignment is strictly necessary.

System Detail & Playground
Real-Time Use: Essential for writing "Clean Code". Using `const` by default prevents accidental bugs where variables are overwritten by other developers.
const system = "VAULT"; let status = "Online"; status = "Deploying"; // OK try { system = "HACKED"; // Error } catch(e) { console.log("System locked:", e.message); } console.log("Current Status:", status);
SYSTEM_OUTPUT:
JS_11

11. call, apply, and bind?

'call' and 'apply' execute a function immediately with a specific 'this' context, while 'bind' creates a new function copy for later use. 'apply' specifically takes arguments as an array, whereas 'call' takes them individually.

System Detail & Playground
Real-Time Use: Used in event handlers to ensure that the `this` keyword correctly points to your Class or Functional Component instead of the HTML element.
const player = { name: "Vimal" }; function greet(rank) { console.log(`Shadow, ${this.name}! Rank: ${rank}`); } greet.call(player, "S-Tier"); // Immediate execution
SYSTEM_OUTPUT:
JS_12

12. What is debouncing and throttling?

Debouncing ensures a function only runs after a specific period of inactivity, while throttling limits a function to running once Every 'X' milliseconds. Both techniques are used to optimize performance by controlling how often expensive functions execute.

System Detail & Playground
Real-Time Use: Debouncing for search bars (don't API call on every keystroke) and Throttling for window resize or scroll events.
console.log("Simulating Scroll..."); let count = 0; const throttle = () => { count++; console.log(`Execution ${count}: Logic processed!`); }; throttle(); // Runs throttle(); // In real use, this would be blocked console.log("Limit reached: Throttling active.");
SYSTEM_OUTPUT:
JS_13Compatibility

13. What are polyfills and transpilers?

A polyfill is code that provides modern functionality on older browsers that do not natively support it, while a transpiler (like Babel) converts modern syntax into a version compatible with those older environments. Together, they allow developers to use the latest language features everywhere.

System Detail & Playground
Real-Time Use: Ensuring your modern `Array.prototype.includes` or `Object.assign` code doesn't crash on Internet Explorer or older Android devices.
console.log("Checking for modern feature..."); if (!Array.prototype.customMsg) { console.log("Polyfill injected: customMsg is now available."); Array.prototype.customMsg = () => "System Mapped"; } console.log([1].customMsg());
SYSTEM_OUTPUT:
JS_14

14. What is Babel and why is it used?

Babel is a toolchain that mainly converts ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments. It allows you to use 'Arrow Functions', 'Classes', and 'Modules' without worrying about browser support.

System Detail & Playground
Real-Time Use: Almost every modern React project uses Babel to convert JSX and ES6 modules into standard JavaScript that the browser can understand.
const modernFn = () => "ES6 Arrow Logic"; console.log("Feature Test:", modernFn()); console.log("Babel would transpile this to 'function() { return ... }'");
SYSTEM_OUTPUT:
JS_15

15. map, filter, reduce, and forEach?

'map' creates a new array by transforming elements, 'filter' creates a subset based on a condition, and 'reduce' boils an array down to a single value. 'forEach' simply iterates through the array without returning a new one.

System Detail & Playground
Real-Time Use: Rendering lists in React (`map`), searching for items (`filter`), and calculating shopping cart totals (`reduce`).
const data = [10, 20, 30]; const total = data.reduce((acc, val) => acc + val, 0); const doubled = data.map(n => n * 2); console.log("Sum result:", total); console.log("Doubled array:", doubled);
SYSTEM_OUTPUT:
JS_16

16. How do you remove duplicate objects?

The most efficient way is using a 'Map' or 'Set' to track unique IDs while filtering the array in O(n) time. Alternatively, one can use 'filter' combined with 'findIndex', though it is less efficient for very large datasets.

System Detail & Playground
Real-Time Use: Cleaning up API responses where the same user or product might appear multiple times in a list.
const users = [{id: 1}, {id: 2}, {id: 1}]; const unique = [...new Map(users.map(u => [u.id, u])).values()]; console.log("Cleaned system users:", unique);
SYSTEM_OUTPUT:

React Mastery Hub

RE_20Engine

1. What is React Fiber?

Reconciliation engine for incremental rendering.

System Detail
Introduced to solve blocking rendering. Breaks work into units of work (fibers) that can be paused/prioritized.
RE_32Optimization

2. useMemo vs useCallback?

useMemo: Cached Value. useCallback: Cached Function.

System Detail
useMemo avoids expensive re-calculations. useCallback prevents child re-renders caused by function reference changes.
RE_42Core

3. Virtual DOM & Reconciliation?

Lightweight DOM copy + Diffing algorithm.

System Detail
React compares the new V-DOM with the old one (Reconciliation) and updates only the necessary nodes in the Real DOM.
JS_17

17. First non-repeating character?

Finding the first unique character in a string involves iterating through it once to build a frequency map and then a second time to identify the first character with a count of one. This is a classic O(n) algorithmic problem used to test string manipulation skills.

System Detail & Playground
Real-Time Use: Used in text processing and compression algorithms to identify unique identifiers or analyze character distributions in large datasets.
const s = "shadow_assassin"; const counts = {}; for (let c of s) counts[c] = (counts[c] || 0) + 1; const unique = s.split('').find(c => counts[c] === 1); console.log("Analyzing:", s); console.log("First Unique Char:", unique);
SYSTEM_OUTPUT:
JS_18

18. How does garbage collection work?

JavaScript uses an automatic memory management process called Garbage Collection, primarily employing the 'Mark-and-Sweep' algorithm. It identifies and reclaims memory that is no longer reachable from the root object, preventing memory leaks.

System Detail & Playground
Real-Time Use: Essential for preventing "Memory Leaks" in long-running apps like music players or code editors where unused variables must be cleared.
let data = { info: "Massive Cache" }; console.log("Allocating memory for data..."); data = null; // Reference broken console.log("System target: Data is now eligible for GC.");
SYSTEM_OUTPUT:
JS_19

19. Mutable vs Immutable data?

Mutable data can be changed after creation (like objects and arrays), whereas immutable data (like strings and numbers) cannot be modified and requires a new copy. Immutability is a core principle in modern libraries like React to ensure predictable state updates.

System Detail & Playground
Real-Time Use: Used in React to detect changes—if the object reference is different (immutable update), React knows it needs to re-render the component.
const original = { level: 99 }; const updated = { ...original, level: 100 }; // Immutable way console.log("Original Level:", original.level); console.log("New Level:", updated.level); console.log("Same object?", original === updated);
SYSTEM_OUTPUT:

Node Engine node

NO_48System

1. Node.js Event Loop work?

Phases: Timers -> I/O -> Poll -> Check -> Close.

System Detail
Single-threaded event loop delegate tasks to Libuv thread pool for OS-level non-blocking calls.

Database Intelligence

DB_56SQL

1. Types of Joins?

Inner, Left, Right, Full Outer.

System Detail
INNER: Common; LEFT: Left + matches; RIGHT: Right + matches; FULL: All.
DB_61NoSQL

2. SQL vs MongoDB?

Relational/Fixed Schema vs Document/Flexible Schema.

System Detail
SQL for rigid structure/ACID; Mongo for high-speed, dynamic data and horizontal scaling.

Security & Ops

SEC_66Danger

1. What is XSS?

Cross-Site Scripting (Injecting malicious JS).

System Detail
Prevent by sanitizing inputs, using Content Security Policy (CSP), and avoiding `dangerouslySetInnerHTML`.

Practical Task Lab

LAB_01O(n)

1. First Non-Repeating Character

function firstUnique(s) {
    const counts = {};
    for (const c of s) counts[c] = (counts[c] || 0) + 1;
    for (const c of s) if (counts[c] === 1) return c;
    return null;
}
LAB_02O(n)

2. Duplicates and Unique Values

function findStats(arr) {
    const map = {}, dups = [], unique = [];
    arr.forEach(n => map[n] = (map[n] || 0) + 1);
    Object.keys(map).forEach(n => map[n] > 1 ? dups.push(n) : unique.push(n));
    return { dups, unique };
}
LAB_06S-Tier Logic

6. Remove Duplicate Objects (Optimized)

function removeDups(arr) {
    const seen = new Set();
    return arr.filter(obj => {
        const k = obj.id;
        return seen.has(k) ? false : seen.add(k);
    });
}