Core Definitions & Key Concepts
Core Definitions & Key Concepts
What is the difference between client-side and server-side JavaScript
Client-side JavaScript runs inside the browser environment (V8, SpiderMonkey) manipulating the DOM, handling user interactions, and initiating HTTP requests. Server-side JavaScript (Node.js, Deno) executes on server operating systems, performing file I/O, database queries, and network socket management.
var, let, and const in modern JavaScript
var: Function-scoped, hoisted withundefinedinitialization, can be re-declared.let: Block-scoped, hoisted into Temporal Dead Zone (TDZ), cannot be re-declared.const: Block-scoped, must be initialized at declaration, creates an immutable variable binding.
What is the Temporal Dead Zone (TDZ)
The state between entering a scope and the variable declaration where let or const variables cannot be accessed. Attempting to read or write them throws a ReferenceError.
The difference between == and === operators
== performs type coercion before comparison (e.g., '5' == 5 is true). === (Strict Equality) checks both value and data type without coercion (e.g., '5' === 5 is false).
What are JavaScript Closures
A closure is the combination of a function bundled together with references to its surrounding lexical state (lexical environment), allowing an inner function to access variables from an outer enclosing scope even after the outer function has finished executing.
What is the JavaScript Event Loop
The concurrency mechanism that continuously monitors the Call Stack and the Callback / Task Queue (and Microtask Queue). When the Call Stack is empty, it pushes waiting callbacks onto the stack for execution.
Macro-tasks and Micro-tasks in the Event Loop
- Micro-tasks: Have higher priority; execute immediately after the current script finishes before rendering (e.g.,
Promise.then,queueMicrotask,MutationObserver). - Macro-tasks: Scheduled after microtasks (e.g.,
setTimeout,setInterval, I/O, UI rendering).
What are Arrow Functions and how does their this binding differ from regular functions
Arrow functions have a compact syntax () => {} and do not possess their own `this` binding. Instead, they capture the this value of the enclosing lexical scope, preventing common scoping bugs in asynchronous callbacks.
JavaScript Prototype and Prototypal Inheritance
Every JavaScript object has an internal [[Prototype]] link pointing to another object. When a property or method is accessed on an object, the engine searches the object itself, then follows the prototype chain upward until the property is found or null is reached.
What is the difference between null and undefined in JavaScript
undefined: Represents a variable that has been declared but not assigned any value (default engine state).null: An intentional assignment representing the explicit absence of any object value.
Conceptual & Architectural Analysis
Conceptual & Architectural Analysis
Compare Asynchronous Patterns in JavaScript: Callbacks, Promises, and Async/Await
| Dimension | Callbacks | Promises (ES6) | Async/Await (ES8) |
|---|---|---|---|
| Syntax Style | Function passed as parameter | .then().catch().finally() | Syntactic sugar over Promises (await) |
| Error Handling | Error-first callbacks ((err, res)) | Centralized .catch() handler | Standard try / catch blocks |
| Readability | Poor ('Callback Hell' / Pyramid of Doom) | Linear chaining | Looks like synchronous procedural code |
| Flow Control | Complex manual nesting | Promise.all(), Promise.race() | Native loop iterations with await |
The Document Object Model (DOM) and Window Object Hierarchy
Browser Object Hierarchy
[ window (Global Object) ]
/ | \ \
[ document ] [ location ] [ history ] [ navigator ]
|
[ <html> element ]
/ \
[ <head> ] [ <body> ]
/ \ / \
[ <title> ] [ <meta> ] [ <h1> ] [ <p> ]- Window Object: The top-level global execution context in a browser representing the browser tab itself.
- Document Object: Represents the root HTML document. Allows programmatic node querying (
querySelector), DOM tree manipulation (createElement,appendChild), and event listener attachment (addEventListener).
Functional Array Operations in ES6: map(), filter(), reduce(), and forEach()
Core Functional Array Methods
- `map(fn)`: Pure, non-mutating method that creates a new array populated with the results of calling a provided transformation function on every element.
- `filter(fn)`: Pure, non-mutating method creating a new array with all elements that pass the truthy predicate test.
- `reduce(fn, init)`: Executes an accumulator function over each element, reducing the array to a single composite output value (sum, grouped object, histogram).
- `forEach(fn)`: Imperative iteration executing side-effects for each element; returns
undefined.
Detail Modern ECMAScript Features: Destructuring, Spread/Rest Operator, and Modules
Modern ES6+ Toolset
- Destructuring Assignment: Unpacking properties from objects or values from arrays into distinct variables:
const { name, age } = user; const [first, ...rest] = items;
- Spread Operator (`...`): Expands an iterable into individual elements (e.g., shallow cloning
{ ...obj }, array merging[...arr1, ...arr2]). - Rest Parameters (`...`): Condenses multiple function arguments into a single formal array parameter.
- ES Modules (ESM): Official standard for modular JavaScript using
import { func } from './module.js'andexport const func = () => {}with static compile-time graph analysis.
Event Propagation in the DOM: Capturing Phase, Target Phase, and Bubbling Phase
DOM Event Flow
[ Document ] -----------> [ Document ] (Capturing: Downwards to target)
| ^
v |
[ <body> ] | (Bubbling: Upwards from target)
| |
v |
[ Target Element: <button> ] -+- Capturing Phase (Trickling): Event travels down from
windowthrough ancestors to the target element. - Target Phase: Event reaches the actual target element that triggered the action.
- Bubbling Phase: Event bubbles upwards from target through ancestors back to
window.
event.stopPropagation()halts traversal;event.preventDefault()stops default browser action.
In-Depth Analysis & Implementation
In-Depth Analysis & Implementation
Provide an In-Depth Architectural Analysis of the V8 JavaScript Engine and the Microtask/Macrotask Event Loop Model
V8 Engine & Event Loop Execution Mechanics
+-----------------------------------------------------------------------------------------+
| V8 ENGINE & RUNTIME ARCHITECTURE |
| |
| +-----------------------------+ +-----------------------------------------------+ |
| | Memory Heap | | Call Stack | |
| | (Object allocations, | | [ executeAsyncLogic() ] | |
| | closures, memory chunks) | | [ main() ] | |
| +-----------------------------+ +-----------------------+-----------------------+ |
| | |
| +---------------------+ |
| v |
| +---------------------------------+---------------------------------+ |
| | | |
| v v |
| +-------------------------------------+ +------------------------------------------+ |
| | Microtask Queue (VIP) | | Macrotask Queue (Task Queue) | |
| | - Promise.then() callbacks | | - setTimeout() callbacks | |
| | - queueMicrotask() | | - setInterval() | |
| | - process.nextTick() (Node.js) | | - DOM Events / I/O | |
| +-------------------------------------+ +------------------------------------------+ |
+-----------------------------------------------------------------------------------------+1. The V8 Compilation Pipeline
- Ignition: Fast bytecode interpreter that parses AST and begins immediate execution without compilation latency.
- TurboFan: Optimizing JIT compiler that takes hot bytecode, observes runtime types (Inline Caching), and compiles highly optimized machine code. If type assumptions are violated, TurboFan de-optimizes back to Ignition bytecode.
2. Event Loop Execution Order Rule
- Execute all synchronous code currently on the Call Stack until empty.
- Execute ALL tasks in the Microtask Queue until completely drained. If a microtask schedules another microtask, it executes in the same cycle.
- Re-render DOM / execute requestAnimationFrame.
- Take ONE task from the Macrotask Queue and push it onto the Call Stack.
- Return to Step 1 and repeat indefinitely.
Design and Build a Robust Asynchronous Data Pipeline in Modern JavaScript with Concurrency Control and Exponential Backoff Retries
Enterprise Async Pipeline Implementation
1/**2 * Executes asynchronous fetch tasks with bounded concurrency and exponential backoff.3 */4async function fetchWithRetry(url, maxRetries = 3, baseDelayMs = 500) {5 for (let attempt = 1; attempt <= maxRetries; attempt++) {6 try {7 const response = await fetch(url);8 if (!response.ok) throw new Error(`HTTP Error ${response.status}`);9 return await response.json();10 } catch (error) {11 if (attempt === maxRetries) throw error;12 const delay = baseDelayMs * Math.pow(2, attempt - 1) + Math.random() * 100;13 console.warn(`Attempt ${attempt} failed for ${url}. Retrying in ${delay.toFixed(0)}ms...`);14 await new Promise(resolve => setTimeout(resolve, delay));15 }16 }17}18
19async function asyncPool(concurrencyLimit, urls, iteratorFn) {20 const ret = [];21 const executing = new Set();22 for (const url of urls) {23 const p = Promise.resolve().then(() => iteratorFn(url));24 ret.push(p);25 executing.add(p);26 const clean = () => executing.delete(p);27 p.then(clean).catch(clean);28 if (executing.size >= concurrencyLimit) {29 await Promise.race(executing);30 }31 }32 return Promise.all(ret);33}Analyze JavaScript Memory Management, Garbage Collection Algorithms (Mark-and-Sweep), and Memory Leak Patterns
Memory Management & Leak Profiling
1. Generational Garbage Collection in V8
- Scavenger (Young Generation): Uses Cheney's copying algorithm. Memory is partitioned into From-Space and To-Space. Active objects are copied to To-Space during minor GC; stale objects are discarded instantly in milliseconds.
- Mark-Sweep-Compact (Old Generation): For long-lived objects. Traces root pointers, marks reachable objects, sweeps dead memory blocks, and compacts fragmented heap.
2. Critical Memory Leak Patterns in Real Apps
- Accidental Global Variables: Assigning
bar = 'data'withoutconst/letattaches references towindowforever. - Forgotten Timers / Intervals: A
setIntervalholding references to outer scoped variables never collected ifclearInterval()is omitted. - Dangling Event Listeners: Attaching listeners to DOM elements that are later removed from the page without calling
removeEventListener(). - Detached DOM Trees: Keeping JavaScript variable references to removed DOM nodes prevents the browser from freeing their entire subtree.
Important Exam Points & Quick Revision
Important Exam Points & Quick Revision
Examiners frequently evaluate: var vs let vs const and TDZ (5 marks), Closures and lexical scope (5/10 marks), and Event Loop Microtask vs Macrotask execution (10/15 marks).
Ready to practice Unit 1?
You've read the core concepts. Take the balanced 10-question practice set to test your mastery!