Modern Web Technologies Notes
DSC course under University of Kerala (UoK FYUGP Regulations). Credits: 4 | 60 Hours (4 Hrs/Week).
Chapter-Wise Module Notes & PDF Downloads
Short Notes
All Modules IncludedComplete syllabus revision notes covering all modules in one single PDF
Module 1
JavaScript: Introduction
Module 2
JavaScript: Arrays, Objects, Events, Form and Exception Handling
Module 3
React JS: Introduction
Module 4
React JS: Events, Styles, Forms in React JS
Module 5
Flexi Module: Cookies in JavaScript & React Router
Read Module Notes Online
Module I: JavaScript: Introduction
Chapter 1: Introduction to JavaScript and Language Fundamentals
1.1 Evolution and Role of JavaScript in Modern Web Architecture
Modern web applications rely on a three-layer client-side architecture: HyperText Markup Language (HTML) defines document structure and semantics, Cascading Style Sheets (CSS) governs visual presentation and responsive layout, and JavaScript supplies programmable behavior, interactivity, and asynchronous communication. Originally created in 1995 by Brendan Eich at Netscape as a lightweight scripting language for browser interactivity, JavaScript has evolved into a standardized general-purpose programming language governed by the ECMAScript specification (ECMA-262). Modern JavaScript engines—such as Google V8 (used in Chrome and Node.js), SpiderMonkey (Firefox), and JavaScriptCore (Safari)—compile JavaScript source code using Just-In-Time (JIT) compilation pipelines, achieving near-native execution speeds.
JavaScript is characterized as a high-level, dynamically typed, prototype-based, multi-paradigm language supporting imperative, object-oriented, and functional programming styles. Unlike statically compiled languages where source code is translated ahead of time into machine binaries, JavaScript is parsed, compiled to bytecode, and optimized at runtime. In the browser environment, JavaScript executes inside a sandboxed host environment that exposes Web APIs such as the Document Object Model (DOM), Browser Object Model (BOM), Fetch API, and Web Storage. With the advent of server-side runtimes like Node.js, JavaScript also powers backend services, build toolchains, and package ecosystems.
1.2 Embedding JavaScript in HTML Documents
Browser engines recognize and execute JavaScript code through the HTML <script> element. Developers can include scripts inline within the HTML document or reference external .js files via the src attribute. External scripts are strongly preferred in production engineering because they promote separation of concerns, enable browser caching across multiple pages, and simplify debugging and version control.
Script placement and loading attributes directly affect page rendering performance. Placing a synchronous <script> tag inside the <head> blocks HTML parsing while the browser downloads and executes the script. Two modern boolean attributes resolve this bottleneck: defer downloads the script in parallel with HTML parsing and guarantees execution in document order right before the DOMContentLoaded event, whereas async downloads in parallel and executes immediately upon completion, potentially out of order.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Script Loading Demo</title> <!-- Downloads in parallel, executes in order after HTML parsing --> <script src="app-core.js" defer></script> <!-- Downloads in parallel, executes immediately when ready --> <script src="analytics.js" async></script> </head> <body> <h1 id="heading">Modern Web Technologies</h1> </body> </html>
1.3 Variables, Scope, Hoisting, and Declaration Keywords
A variable is a named storage binding in memory that holds a value or a reference to an object. JavaScript provides three declaration keywords: var, let, and const. Understanding their scoping rules, mutability semantics, and hoisting behavior is essential for writing defect-free code.
The legacy var keyword is function-scoped (or globally scoped if declared outside any function) and ignores block boundaries such as if or for blocks. Declarations with var are hoisted to the top of their enclosing function or global context and initialized with an uninitialized sentinel state before their assignment line executes. Moreover, var permits accidental redeclaration in the same scope, which frequently causes subtle bugs in large codebases.
Introduced in ECMAScript 2015 (ES6), let and const are block-scoped, meaning they exist only within the nearest enclosing curly braces { ... }. Both are hoisted conceptually, but they remain in the Temporal Dead Zone (TDZ) from the start of the block until the declaration statement is reached; accessing them inside the TDZ throws a ReferenceError. While let allows reassignment of the variable binding, const creates a constant binding that cannot be reassigned after initialization. Importantly, const guarantees immutability of the binding, not deep immutability of an object or array's internal properties.
| Feature | var (ES5) | let (ES6) | const (ES6) |
|---|---|---|---|
| Scope | Function or Global scope | Block scope ({ ... }) |
Block scope ({ ... }) |
| Hoisting Behavior | Hoisted and auto-initialized | Hoisted in Temporal Dead Zone | Hoisted in Temporal Dead Zone |
| Reassignment | Allowed | Allowed | Prohibited (throws TypeError) |
| Redeclaration in Same Scope | Allowed silently | Prohibited (SyntaxError) | Prohibited (SyntaxError) |
| Initialization Required | Optional | Optional | Mandatory at declaration |
function demonstrateScope() {
const courseCode = "UK2DSCCAP105";
let enrollmentCount = 45;
if (enrollmentCount > 40) {
let section = "Batch A";
enrollmentCount += 5;
console.log(section, enrollmentCount); // Batch A 50
}
// Constant object reference: properties can still be updated
const syllabus = { moduleCount: 5, level: "FYUGP" };
syllabus.moduleCount = 6; // Valid mutation of property
console.log(courseCode, syllabus.moduleCount);
}
demonstrateScope();1.4 Data Types and Dynamic Typing
JavaScript is dynamically typed: variables do not carry fixed type annotations; instead, values carry types at runtime. The ECMAScript specification defines seven primitive data types and one non-primitive (reference) type, Object.
- Number: Represents both integer and floating-point values using IEEE 754 double-precision 64-bit binary format. Special numeric values include
Infinity,-Infinity, and the invalid-number sentinel produced by failed arithmetic such as dividing zero by zero or parsing non-numeric text. - BigInt: Represents integers of arbitrary precision beyond the safe integer limit , created by appending
nto an integer literal (for example,9007199254740993n). - String: Immutable sequences of UTF-16 code units enclosed in single quotes, double quotes, or backticks (template literals supporting multi-line text and interpolation).
- Boolean: Logical entity having exactly two values:
trueandfalse, used extensively in branching and loop predicates. - Uninitialized Primitive: A distinct primitive state representing a declared variable that has not yet been assigned a value, or a function that completes without an explicit return statement.
- Null: Represents the intentional absence of any object value, explicitly assigned by a programmer to indicate an empty reference.
- Symbol: Unique and immutable primitive identifier introduced in ES6, primarily used as collision-free property keys on objects.
- Object (Reference Type): Mutable collection of key-value pairs and more complex entities including plain objects, arrays, functions, dates, and regular expressions.
A critical distinction exists between primitive values and reference values in memory. Primitives are stored directly on the execution stack and copied by value: assigning one primitive variable to another creates an independent duplicate. Objects are allocated on the heap, and variables store a memory reference (pointer) to that heap address. Assigning an object variable to another copies the reference, meaning both variables point to the same underlying object.
The unary typeof operator returns a string indicating the type of its operand (such as "number", "string", "boolean", "object", or "function"). Notably, typeof null evaluates to "object" due to a historic implementation quirk preserved for backward compatibility. Type conversion can be explicit (using Number(), String(), Boolean(), parseInt(), parseFloat()) or implicit (type coercion performed automatically by operators such as + when combining a string and a number).
Chapter 2: Operators, Expressions, and Control Structures
2.1 Expressions, Operators, and Precedence
An expression is any valid unit of code that resolves to a single value, whereas operators are symbols or keywords that perform computations on one, two, or three operands. Operator precedence determines the order in which operators are evaluated in complex expressions, and associativity determines evaluation direction (left-to-right or right-to-left) when operators share the same precedence level.
| Operator Category | Operators | Primary Purpose and Behavior |
|---|---|---|
| Arithmetic | +, -, *, /, %, **, ++, -- |
Standard math, remainder modulo, exponentiation (**), and prefix/postfix increment or decrement. |
| Assignment | =, +=, -=, *=, /=, %=, ??= |
Assigns or updates variable bindings; compound operators combine arithmetic with assignment. |
| Comparison | ===, !==, ==, !=, >, <, >=, <= |
Strict equality (===) checks both value and type without coercion; loose equality (==) coerces operands. |
| Logical | &&, ||, !, ?? |
Boolean conjunction, disjunction, negation, and nullish coalescing (fallback only for null or uninitialized values). |
| Conditional (Ternary) | cond ? expr1 : expr2 |
Compact inline expression returning expr1 if truthy or expr2 otherwise. |
| String & Template | +, +=, backticks `...` |
Concatenates strings or embeds expressions cleanly inside template literals. |
In truthy and falsy evaluation, JavaScript treats exactly six values as falsy in boolean contexts: false, 0 (and -0, 0n), empty string "", null, the uninitialized primitive, and the invalid-number sentinel. Every other value—including non-empty strings like "0", empty arrays [], and empty objects {}—evaluates as truthy. Logical operators && and || implement short-circuit evaluation: they stop evaluating as soon as the outcome is determined and return the deciding operand itself rather than a coerced boolean.
const rawScore = 0;
const fallbackScore = rawScore || 10; // 10 (0 is falsy)
const safeScore = rawScore ?? 10; // 0 (0 is neither null nor missing)
console.log(5 == "5"); // true (loose equality coerces string to number)
console.log(5 === "5"); // false (strict equality checks type and value)
const studentName = "Ananya";
const credits = 4;
const summary = `Student ${studentName} earned ${credits} credits (Score: ${safeScore}).`;
console.log(summary);2.2 Conditional Control Structures
Control structures alter the sequential top-to-bottom execution flow of a program based on runtime conditions. Conditional branching uses if, else if, else, and switch statements.
An if statement evaluates a predicate expression; if truthy, its block executes. Chaining else if clauses allows mutually exclusive multi-way branching, where the first matching condition executes and remaining branches are skipped. When branching depends on comparing a single expression against multiple discrete constant values using strict equality (===), a switch statement improves readability. Each case clause should terminate with a break statement to prevent execution from falling through into subsequent cases, and an optional default branch handles unmatched values.
function classifyGrade(marks) {
let grade;
if (marks >= 90) {
grade = "A+";
} else if (marks >= 80) {
grade = "A";
} else if (marks >= 70) {
grade = "B";
} else if (marks >= 60) {
grade = "C";
} else {
grade = "F";
}
switch (grade) {
case "A+":
case "A":
return "Distinction (" + grade + ")";
case "B":
case "C":
return "Pass (" + grade + ")";
default:
return "Needs Improvement";
}
}
console.log(classifyGrade(84)); // Distinction (A)2.3 Loop Statements and Iteration Control
Loops repeatedly execute a block of code as long as a termination condition holds. JavaScript supports counter-controlled, condition-controlled, and collection-oriented loops:
- for Loop: Combines initialization, continuation condition, and update expression in a compact header. Ideal when the number of iterations is known beforehand.
- while Loop: Entry-controlled loop that checks the condition before each iteration; if initially false, the body executes zero times.
- do...while Loop: Exit-controlled loop that executes the loop body at least once before testing the continuation condition.
- for...of Loop: Iterates directly over values of iterable objects such as arrays, strings, Maps, and Sets.
- for...in Loop: Iterates over enumerable string keys (property names) of an object; generally avoided for arrays to prevent iterating over inherited or non-index properties.
The break statement immediately exits the innermost enclosing loop, whereas continue skips the remainder of the current iteration and proceeds to the next loop cycle. When working with nested loops, labeled statements (e.g., outerLoop: for (...)) allow break outerLoop; to exit multiple loop levels cleanly.
// 1. Standard for loop: sum of first 5 natural numbers
let total = 0;
for (let i = 1; i <= 5; i++) {
total += i;
}
// 2. while loop with continue and break
let step = 0;
while (step < 10) {
step++;
if (step % 2 === 0) continue; // skip even numbers
if (step > 7) break; // stop after 7
console.log("Odd step:", step);
}
// 3. do...while loop: guaranteed single execution
let attempts = 0;
do {
attempts++;
} while (attempts < 1);
// 4. for...of over an array
const topics = ["Variables", "Operators", "Loops"];
for (const topic of topics) {
console.log("Topic:", topic);
}Chapter 3: Functions, Closures, and Browser Dialog Boxes
3.1 Declaring Functions: Declarations, Expressions, and Arrows
Functions are first-class citizens in JavaScript, meaning they can be assigned to variables, passed as arguments to other functions, returned from functions, and stored inside data structures. Modularizing logic into well-named functions eliminates code duplication and simplifies testing.
A function declaration uses the function keyword followed by a name, parameter list, and body. Function declarations are completely hoisted—both their name and implementation are available throughout their enclosing scope before the line where they appear. A function expression assigns an anonymous or named function to a variable; only the variable binding follows hoisting rules, so the function cannot be invoked before its assignment executes.
Introduced in ES6, arrow functions provide concise syntax using the fat arrow =>. When an arrow function contains a single expression without curly braces, it performs an implicit return. Crucially, arrow functions do not bind their own this context or arguments object; instead, they inherit this lexically from the surrounding scope, making them ideal for callbacks and React event handlers.
// Function declaration (hoisted)
console.log(square(4)); // 16
function square(n) {
return n * n;
}
// Function expression (not callable before initialization)
const cube = function (n) {
return n * n * n;
};
// Arrow function with implicit return
const areaOfCircle = (radius) => Math.PI * radius * radius;
// Arrow function with explicit block body
const formatPrice = (amount, currency = "INR") => {
const rounded = amount.toFixed(2);
return currency + " " + rounded;
};
console.log(cube(3), areaOfCircle(2).toFixed(2), formatPrice(499.5));3.2 Parameters, Arguments, and Return Values
Parameters are the named placeholders listed in a function's definition, whereas arguments are the actual values supplied by the caller during invocation. JavaScript does not enforce argument count matching at compile time: omitted parameters receive the uninitialized primitive state unless a default parameter (e.g., taxRate = 0.18) is specified. Extra arguments can be captured cleanly as a true array using the ES6 rest parameter syntax (...items), which must appear as the final parameter.
Primitive arguments are passed by value, so modifying a parameter inside the function does not affect the caller's variable. Object and array arguments pass a copy of their memory reference, meaning mutating an object's property inside a function is visible outside, though reassigning the parameter variable itself is not. A function terminates and hands back a single result via the return statement. Returning early on invalid input—known as the guard clause pattern—reduces nested conditionals and improves code clarity.
3.3 Lexical Scope, Closures, and Higher-Order Functions
Lexical scoping means that a function's variable visibility is determined by where the function is physically written in the source code, not where it is called. A closure is formed whenever an inner function retains access to variables from its outer enclosing function even after the outer function has finished executing and returned. Closures enable data encapsulation (private state) and function factories.
A higher-order function is a function that either accepts one or more functions as arguments (callbacks) or returns a new function. Built-in methods such as setTimeout, addEventListener, and array transformations rely heavily on higher-order functions.
function createCounter(initialValue = 0) {
let count = initialValue; // Private variable enclosed by inner functions
return {
increment() {
count += 1;
return count;
},
decrement() {
count -= 1;
return count;
},
getValue() {
return count;
}
};
}
const pageVisits = createCounter(10);
console.log(pageVisits.increment()); // 11
console.log(pageVisits.increment()); // 12
console.log(pageVisits.getValue()); // 123.4 Browser Dialog Boxes: Alert, Confirm, and Prompt
The Browser Object Model (BOM) exposes three built-in modal dialog methods on the global window object: alert(), confirm(), and prompt(). All three are synchronous and blocking—they pause JavaScript execution and user interaction with the underlying page until the user dismisses the dialog.
| Dialog Method | UI Controls | Return Value | Typical Use Case |
|---|---|---|---|
window.alert(msg) |
Message + OK button | No return value (uninitialized) | Displaying brief notifications or urgent warnings. |
window.confirm(msg) |
Message + OK and Cancel | true (OK) or false (Cancel) |
Verifying destructive actions such as record deletion. |
window.prompt(msg, defaultVal) |
Message + text input + OK/Cancel | Entered string (OK) or null (Cancel) |
Collecting quick single-field text input during learning demos. |
A frequent pitfall with prompt() is that it always returns a string when the user clicks OK, even if digits were typed. Therefore, numeric inputs must be explicitly converted using Number() or parseInt() before arithmetic operations, and callers must check for null to handle cancellation gracefully. In modern production web applications, native dialog boxes are largely replaced by non-blocking HTML/CSS modal components because browser dialogs cannot be styled and freeze the main UI thread.
function processOrder() {
const proceed = window.confirm("Do you want to place the textbook order?");
if (!proceed) {
window.alert("Order cancelled by user.");
return;
}
const qtyText = window.prompt("Enter quantity (1 to 10):", "1");
if (qtyText === null) {
window.alert("Quantity entry aborted.");
return;
}
const quantity = parseInt(qtyText, 10);
if (!Number.isFinite(quantity) || quantity < 1 || quantity > 10) {
window.alert("Please enter a valid whole number between 1 and 10.");
return;
}
const totalCost = quantity * 250;
window.alert("Order confirmed! Total payable: INR " + totalCost);
}Chapter 4: Type Conversion, Execution Context, and Worked Patterns
4.1 Explicit Conversion, Implicit Coercion, and Strict Mode
Because JavaScript is dynamically typed, operators frequently coerce operands from one type to another automatically. Implicit coercion occurs when the binary + operator encounters a string operand—converting the other operand to a string and performing concatenation—whereas arithmetic operators like -, *, and / coerce string operands to numbers. While convenient in simple scripts, implicit coercion can mask subtle logic errors when validating user input.
Explicit type conversion makes programmer intent unambiguous. Calling Number("42") converts an entire string strictly (returning an invalid-number sentinel if non-numeric characters appear), whereas parseInt("42px", 10) parses leading integer digits up to the first non-digit character. Always pass radix 10 to parseInt() to prevent older engines from interpreting leading zeros as octal. Similarly, Boolean(val) or double negation !!val converts any expression into a strict true or false.
| Input Expression | Number(x) |
parseInt(x, 10) |
Boolean(x) |
|---|---|---|---|
"42" |
42 |
42 |
true |
"42px" |
Invalid numeric result | 42 |
true |
"" (empty string) |
0 |
Invalid numeric result | false |
null |
0 |
Invalid numeric result | false |
"0" |
0 |
0 |
true |
Enabling Strict Mode by placing "use strict"; at the top of a script or function instructs the JavaScript engine to enforce stricter parsing and runtime error checking. Strict mode converts silent failures into thrown exceptions: assigning to an undeclared variable throws a ReferenceError instead of creating an accidental global variable, assigning to a read-only property throws a TypeError, and duplicate parameter names are rejected at parse time. ES6 modules and React codebases execute in strict mode automatically.
4.2 Execution Context, Call Stack, and Recursion
Every time a JavaScript script starts or a function is invoked, the engine creates an Execution Context consisting of a Variable Environment, a Lexical Environment (scope chain), and a this binding. Execution contexts are managed on a Last-In, First-Out (LIFO) structure called the Call Stack. When function A calls function B, B's frame is pushed onto the stack above A; when B returns, its frame is popped and execution resumes inside A.
A recursive function is a function that invokes itself to solve smaller subproblems of the same structure until reaching a terminating base case. Without a reachable base case, recursive calls exhaust the Call Stack and throw a RangeError: Maximum call stack size exceeded.
"use strict";
// Recursive factorial with base-case guard
function factorial(n) {
if (!Number.isInteger(n) || n < 0) {
throw new RangeError("Factorial requires a non-negative integer.");
}
if (n <= 1) return 1;
return n * factorial(n - 1);
}
// Immediately Invoked Function Expression (IIFE) isolating initialization
(function initModuleBanner() {
const version = "1.0.0";
console.log("JS Core Runtime initialized (v" + version + ")");
})();
// Interactive SGPA calculation using prompt, confirm, and loop control
function runSgpaAssistant() {
const subjectCountText = window.prompt("How many subjects do you want to enter?", "4");
if (subjectCountText === null) return;
const subjectCount = parseInt(subjectCountText, 10);
if (!Number.isFinite(subjectCount) || subjectCount <= 0) {
window.alert("Invalid subject count.");
return;
}
let totalGradePoints = 0;
for (let i = 1; i <= subjectCount; i++) {
const markText = window.prompt("Enter marks (0-100) for Subject " + i + ":", "75");
if (markText === null) {
if (window.confirm("Cancel entire calculation?")) return;
i--;
continue;
}
const mark = Number(markText);
if (!Number.isFinite(mark) || mark < 0 || mark > 100) {
window.alert("Marks must be between 0 and 100. Re-enter.");
i--;
continue;
}
totalGradePoints += mark / 10;
}
const sgpa = (totalGradePoints / subjectCount).toFixed(2);
window.alert("Estimated SGPA: " + sgpa + " | 5! = " + factorial(5));
}Module II: JavaScript: Arrays, Objects, Events, Form and Exception Handling
Chapter 1: Arrays, Objects, and Iteration Patterns
1.1 Working with JavaScript Arrays
An array in JavaScript is an ordered, zero-indexed, dynamically resizable collection capable of storing heterogeneous values—numbers, strings, booleans, objects, or even nested arrays. Arrays are specialized objects whose length property updates automatically as elements are added or removed. While new Array() exists, the array literal syntax [...] is the standard idiom because it avoids ambiguity when passing a single numeric argument.
Modern JavaScript distinguishes between mutating methods that modify the original array in place and non-mutating methods that return a new array or derived value without altering the source array. Immutability is especially critical in React state management, where direct array mutation prevents change detection.
| Method | Category | Behavior and Return Value |
|---|---|---|
push() / pop() |
Mutating (End) | Adds element(s) to end (returns new length) / removes last element (returns removed item). |
unshift() / shift() |
Mutating (Start) | Adds element(s) to front / removes first element (shifts remaining indices). |
splice(start, delCount, ...items) |
Mutating (Anywhere) | Removes, replaces, or inserts elements at a given index; returns array of deleted items. |
slice(start, end) |
Non-Mutating | Returns a shallow copy of a subarray from start up to (excluding) end. |
map(fn) |
Higher-Order (Non-Mutating) | Transforms every element using callback fn and returns a new array of equal length. |
filter(fn) |
Higher-Order (Non-Mutating) | Returns a new array containing only elements for which predicate fn returns truthy. |
reduce(fn, init) |
Higher-Order (Non-Mutating) | Folds array elements left-to-right into a single accumulated value (sum, object, or array). |
const marks = [78, 92, 65, 88, 54];
// Non-mutating pipeline: filter passing marks, add 5 bonus, compute total
const passed = marks.filter((m) => m >= 60);
const boosted = passed.map((m) => Math.min(100, m + 5));
const sum = boosted.reduce((acc, val) => acc + val, 0);
// Destructuring and spread operator
const [firstScore, secondScore, ...remainingScores] = boosted;
const combined = [...marks, 95, 100];
console.log({ passed, boosted, sum, firstScore, secondScore, remainingScores, combined });1.2 Working with JavaScript Objects and JSON
Objects represent structured entities as unordered collections of key-value pairs (properties). Keys are strings or Symbols, and values may be primitives, nested objects, or functions (called methods when attached to an object). Properties are accessed via dot notation (student.name) when the key is a valid static identifier, or bracket notation (student[dynamicKey]) when the key is stored in a variable or contains spaces/hyphens.
Inside an object method, the this keyword dynamically refers to the object through which the method was invoked. ES6 introduced object destructuring (const { name, age } = student), shorthand property names, computed property keys, and object spread ({ ...defaults, ...overrides }) for shallow cloning and merging. Built-in static helpers Object.keys(obj), Object.values(obj), and Object.entries(obj) convert an object's own enumerable properties into arrays for convenient processing.
JavaScript Object Notation (JSON) is a lightweight, language-independent data interchange format derived from JavaScript object syntax. Unlike JS object literals, JSON requires double-quoted property keys and excludes functions or trailing commas. JSON.stringify(obj) serializes an object into a JSON string for network transmission or storage, while JSON.parse(str) reconstructs a live JavaScript object from a JSON string.
const student = {
id: "BCA2026-04",
name: "Karthik Nair",
scores: { web: 91, dbms: 86 },
getSummary() {
return this.name + " (" + this.id + ") - Web: " + this.scores.web;
}
};
// Destructuring with nested extraction
const { name, scores: { web } } = student;
const updatedStudent = { ...student, semester: 2 };
// JSON conversion
const jsonPayload = JSON.stringify(updatedStudent);
const parsedCopy = JSON.parse(jsonPayload);
console.log(student.getSummary(), name, web, parsedCopy.semester);1.3 Iterating Through Arrays and Objects
Selecting the right iteration mechanism prevents off-by-one bugs and prototype pollution issues. For arrays, for...of provides clean access to values and supports break and continue, whereas array.forEach((item, index) => ...) executes a callback per element without supporting early termination. For objects, for...in traverses all enumerable keys (including inherited ones unless guarded with Object.hasOwn(obj, key)), whereas iterating over Object.entries(obj) with for...of cleanly destructures each [key, value] pair safely.
const inventory = { keyboards: 14, mice: 22, monitors: 9 };
// Iterating object key-value pairs cleanly
for (const [item, count] of Object.entries(inventory)) {
console.log("Item:", item, "-> Stock:", count);
}
// Guarded for...in iteration
for (const key in inventory) {
if (Object.hasOwn(inventory, key)) {
console.log(key + ": " + inventory[key]);
}
}Chapter 2: Browser Events and Interactive Event Handling
2.1 Event Model, Listeners, and Propagation
Browser applications are inherently event-driven: the JavaScript runtime waits in an event loop and invokes registered callback functions whenever user actions or browser state changes occur. The recommended way to attach behavior to a DOM node is element.addEventListener(eventType, handler, options). Unlike assigning element.onclick = fn (which overwrites any prior handler) or embedding inline HTML attributes like onclick="..." (which mixes markup and logic), addEventListener allows multiple independent listeners on the same element and clean detachment via removeEventListener.
When an event fires on a nested DOM element, it travels through three phases: the capturing phase (top-down from window and document toward the target), the target phase (on the originating element), and the bubbling phase (bottom-up back to window). By default, addEventListener listens during the bubbling phase. Calling event.stopPropagation() halts further upward or downward travel, while event.preventDefault() cancels the browser's default action (such as navigating on a link click or reloading on form submission). Event delegation exploits bubbling by attaching a single listener to a parent container and inspecting event.target to handle clicks from many child elements efficiently.
2.2 Click Events, Mouse Events, and Keyboard Events
Interactive interfaces respond primarily to pointer and keyboard input:
- Click Events:
clickfires after a complete press-and-release of the primary pointer button or Enter key activation on a focused button/link;dblclickfires on two rapid clicks;contextmenufires on right-click (often intercepted to display custom menus). - Mouse Events:
mousedownandmouseuptrack individual press/release phases;mousemovetracks cursor coordinates continuously (event.clientX,event.clientY);mouseenterandmouseleavetrigger only when crossing the bound element itself without bubbling, whereasmouseoverandmouseoutbubble when entering child elements. - Keyboard Events:
keydownfires immediately when any key is pressed (repeating if held down) and is preferred over the deprecatedkeypressevent;keyupfires when the key is released. TheEventobject exposesevent.key(the character or logical key name like"Enter"or"Escape"),event.code(physical key position like"KeyA"), and modifier booleans (ctrlKey,shiftKey,altKey).
const listContainer = document.getElementById("task-list");
const coordDisplay = document.getElementById("coords");
// Event delegation for click events on dynamic list items
listContainer.addEventListener("click", (event) => {
if (event.target.matches("button.delete-btn")) {
event.target.parentElement.remove();
}
});
// Mouse movement coordinate tracking
listContainer.addEventListener("mousemove", (event) => {
coordDisplay.textContent = "X: " + event.clientX + ", Y: " + event.clientY;
});
// Keyboard shortcut handling (Ctrl + S)
document.addEventListener("keydown", (event) => {
if (event.ctrlKey && event.key.toLowerCase() === "s") {
event.preventDefault();
console.log("Custom save shortcut triggered.");
}
});Chapter 3: HTML Forms, Client-Side Validation, and Exception Handling
3.1 Working with Forms in JavaScript
HTML forms collect structured user input using controls such as <input>, <select>, and <textarea>. JavaScript accesses forms through document.forms or standard DOM queries like document.getElementById(). Input values are read from the .value property for text fields and dropdowns, or .checked (boolean) for checkboxes and radio buttons. Key form events include input (fires on every keystroke or value change), change (fires when a field loses focus after modification or when a select/checkbox changes), focus/blur, and submit on the parent <form> element.
3.2 Client-Side Form Validation
Client-side validation verifies user input in the browser before transmitting data to a server, providing immediate feedback and reducing unnecessary network round-trips. Validation combines declarative HTML5 constraint attributes (required, minlength, maxlength, min, max, type="email", pattern) with programmatic JavaScript checks using regular expressions (RegExp) and custom business rules. Because client-side checks can be bypassed by disabling JavaScript or crafting direct HTTP requests, client-side validation must always be paired with server-side validation for security.
const regForm = document.getElementById("register-form");
const errorBox = document.getElementById("form-error");
regForm.addEventListener("submit", (event) => {
const email = regForm.elements["email"].value.trim();
const phone = regForm.elements["phone"].value.trim();
const password = regForm.elements["password"].value;
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const phoneRegex = /^[6-9]\d{9}$/;
const errors = [];
if (!emailRegex.test(email)) errors.push("Enter a valid email address.");
if (!phoneRegex.test(phone)) errors.push("Phone must be a 10-digit Indian mobile number.");
if (password.length < 8) errors.push("Password must contain at least 8 characters.");
if (errors.length > 0) {
event.preventDefault(); // Block form submission
errorBox.textContent = errors.join(" ");
} else {
errorBox.textContent = "";
}
});3.3 Exception Handling: try, catch, finally, and throw
Runtime exceptions occur when an operation cannot complete normally—such as parsing malformed JSON, accessing a property on null, or encountering a network timeout. Without structured exception handling, an uncaught exception terminates script execution immediately. Common built-in error constructors include SyntaxError, ReferenceError, TypeError, RangeError, and URIError.
The try...catch...finally construct isolates risky code inside the try block. If an exception is thrown, control transfers immediately to the catch (error) block, which receives an Error instance containing error.name, error.message, and error.stack. The optional finally block executes unconditionally after try and catch finish—even if a return statement is encountered—making it ideal for releasing resources such as closing loading spinners or file handles. Developers can also raise domain-specific failures using throw new Error("...") or by extending the base Error class.
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
function parseUserProfile(rawJson) {
try {
const profile = JSON.parse(rawJson);
if (!profile.username) {
throw new ValidationError("Profile JSON is missing required username field.");
}
return profile;
} catch (err) {
if (err instanceof ValidationError) {
console.warn("Validation issue:", err.message);
} else {
console.error("JSON parsing failed:", err.name, err.message);
}
return null;
} finally {
console.log("Profile parsing attempt completed.");
}
}
parseUserProfile('{"role": "student"}');Chapter 4: Advanced Data Pipelines, Event Architecture, and Validation APIs
4.1 Multidimensional Arrays, Numeric Sorting, and Immutability
JavaScript arrays naturally model two-dimensional tables or matrices as arrays of arrays, accessed via row-column indexing matrix[row][col]. When sorting arrays with Array.prototype.sort(), developers must beware of a classic pitfall: without a comparator function, sort() converts elements to strings and sorts lexicographically, placing 100 before 20. Always supply a numeric comparator (a, b) => a - b for ascending order, and copy the array first ([...arr].sort(...) or ES2023 toSorted()) to avoid mutating source data.
When cloning nested objects or arrays, the spread operator ({ ...obj }) and Object.assign() perform only a shallow copy: top-level properties are duplicated, but nested objects still share references with the original. For true deep cloning of structured data, modern browsers provide structuredClone(obj). To enforce runtime immutability on configuration objects, Object.freeze(config) prevents adding, deleting, or modifying top-level properties.
const courses = [
{ code: "UK2DSCCAP105", title: "Modern Web Technologies", enrolled: 62 },
{ code: "UK2DSCCAP104", title: "Data Structures", enrolled: 58 },
{ code: "UK2DSCCAP103", title: "Database Management", enrolled: 71 }
];
// Non-mutating sort by enrollment descending
const rankedCourses = [...courses].sort((a, b) => b.enrolled - a.enrolled);
const totalSeats = courses.reduce((sum, c) => sum + c.enrolled, 0);
// 2D attendance matrix traversal (3 students x 4 weeks)
const attendance = [
[1, 1, 0, 1],
[1, 1, 1, 1],
[0, 1, 1, 1]
];
for (let r = 0; r < attendance.length; r++) {
const presentCount = attendance[r].reduce((acc, v) => acc + v, 0);
console.log("Student " + (r + 1) + " attended " + presentCount + " weeks.");
}
console.log("Top course:", rankedCourses[0].code, "Total seats:", totalSeats);4.2 Event Propagation Phases, Options, and Custom Events
Understanding the DOM event lifecycle is vital when building nested interactive widgets such as dropdowns, modals, and data tables. Calling addEventListener(type, fn, { capture: true }) registers a listener in the top-down capturing phase; { once: true } automatically detaches the listener after its first invocation; and { passive: true } informs the browser that preventDefault() will not be called, enabling smooth 60fps scroll performance on wheel and touchstart events.
Applications can also define and dispatch domain-specific events using the CustomEvent constructor, allowing decoupled UI modules to communicate cleanly without tight coupling.
| Event Category | Key Event Types | Important Event Properties |
|---|---|---|
| Pointer & Click | click, dblclick, contextmenu |
button, target, currentTarget, ctrlKey |
| Mouse Movement | mousedown, mouseup, mousemove, mouseenter, mouseleave |
clientX, clientY, pageX, pageY, relatedTarget |
| Keyboard | keydown, keyup |
key, code, repeat, shiftKey, altKey, metaKey |
| Form & Input | input, change, focus, blur, submit, reset |
target.value, target.checked, target.validity |
4.3 HTML5 Constraint Validation API and Defensive Error Handling
Beyond manual regular expressions, every HTML form control exposes the Constraint Validation API via element.validity (a ValidityState object with boolean flags such as valueMissing, typeMismatch, patternMismatch, tooShort, and valid). Calling input.setCustomValidity("Message") sets a custom browser validation error, while passing an empty string "" clears it. Combining live input event feedback with try...catch blocks around JSON parsing or local storage operations guarantees resilient form workflows.
const passwordInput = document.getElementById("pwd");
const confirmInput = document.getElementById("pwd-confirm");
function validatePasswordMatch() {
if (confirmInput.value !== passwordInput.value) {
confirmInput.setCustomValidity("Passwords do not match.");
} else {
confirmInput.setCustomValidity("");
}
}
passwordInput.addEventListener("input", validatePasswordMatch);
confirmInput.addEventListener("input", validatePasswordMatch);
// Dispatching a custom application event after successful validation
function notifyRegistrationSuccess(studentId) {
const evt = new CustomEvent("student:registered", {
detail: { studentId, timestamp: Date.now() },
bubbles: true
});
document.dispatchEvent(evt);
}
document.addEventListener("student:registered", (e) => {
console.log("Registered student ID:", e.detail.studentId);
});Chapter 5: Practical DOM Form Architecture, Error Recovery, and Prototypes
5.1 Object Prototypes, Property Descriptors, and Method Sharing
Every JavaScript object maintains an internal hidden link ([[Prototype]]) to another object, forming a prototype chain. When a property or method is accessed on an object and is not found directly on the object itself, the JavaScript engine walks up the prototype chain until it finds the property or reaches null. Built-in methods such as Array.prototype.map and Object.prototype.hasOwnProperty reside on shared prototype objects so that thousands of instances do not duplicate function memory.
Object properties also carry internal metadata attributes known as property descriptors: value, writable (whether the value can be reassigned), enumerable (whether it appears in for...in or Object.keys()), and configurable (whether the property can be deleted or reconfigured). Using Object.defineProperty() or Object.freeze() allows library authors to lock down sensitive configuration objects against accidental mutation in strict mode.
5.2 Defensive Asynchronous Error Handling and Form Recovery
Modern form submissions frequently transmit validated payloads to backend REST endpoints using the fetch() API. Because network failures (offline connections, DNS timeouts) reject promises while HTTP error responses (such as 400 Bad Request or 500 Internal Server Error) resolve normally with response.ok === false, robust client code must inspect response.ok inside an async try...catch...finally block, restore submit button interactivity in finally, and display clear inline recovery messages to the user.
const admissionForm = document.getElementById("admission-form");
const submitBtn = document.getElementById("submit-btn");
const feedback = document.getElementById("feedback");
function validateAdmissionFields(data) {
const errors = {};
if (data.fullName.length < 3) {
errors.fullName = "Full name must be at least 3 characters.";
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) {
errors.email = "Provide a valid academic email address.";
}
const ageNum = Number(data.age);
if (!Number.isInteger(ageNum) || ageNum < 16 || ageNum > 60) {
errors.age = "Age must be a whole number between 16 and 60.";
}
return errors;
}
admissionForm.addEventListener("submit", async (event) => {
event.preventDefault();
const payload = {
fullName: admissionForm.elements["fullName"].value.trim(),
email: admissionForm.elements["email"].value.trim(),
age: admissionForm.elements["age"].value.trim()
};
const validationErrors = validateAdmissionFields(payload);
if (Object.keys(validationErrors).length > 0) {
feedback.textContent = Object.values(validationErrors).join(" | ");
return;
}
submitBtn.disabled = true;
try {
const response = await fetch("/api/admissions", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload)
});
if (!response.ok) {
throw new Error("Server rejected submission (HTTP " + response.status + ")");
}
const result = await response.json();
feedback.textContent = "Application saved! Reference ID: " + result.refId;
admissionForm.reset();
} catch (err) {
feedback.textContent = "Submission failed: " + err.message;
} finally {
submitBtn.disabled = false;
}
});5.3 Interactive Keyboard and Mouse Accessibility Checklist
When building custom interactive widgets using click, mouse, and key events, developers must ensure full keyboard accessibility alongside pointer support. Every clickable control should use semantic <button> or <a href> elements rather than bare <div> tags, or explicitly support Enter and Space keydown handlers. Similarly, hover-triggered tooltips bound to mouseenter and mouseleave should be mirrored with focus and blur handlers so keyboard-only users receive identical feedback.
Chapter 6: Regular Expressions, Map/Set Collections, and Defensive Coding
6.1 Regular Expressions for Client-Side Form Validation
A Regular Expression (RegExp) is a compact pattern-matching language built into JavaScript for validating, searching, and extracting structured text such as email addresses, postal codes, and password complexity rules. Regex patterns can be constructed using literal slashes (/pattern/flags) when static, or new RegExp(patternStr, flags) when assembled dynamically at runtime. Common flags include i (case-insensitive) and g (global match).
| Token | Meaning | Validation Example |
|---|---|---|
^ and $ |
Start and end of string anchors | /^BCAd{4}$/ matches exact 7-char ID |
d, w, s |
Digit, word char, whitespace | /^d{6}$/ validates 6-digit PIN code |
+, *, ?, {m,n} |
Quantifiers (1+, 0+, 0-1, range) | /^[A-Za-z]{2,30}$/ validates name length |
(?=...) |
Positive lookahead assertion | Enforces uppercase + digit in strong passwords |
6.2 ES6 Map and Set vs Plain Objects and Arrays
While plain objects and arrays cover most data modeling needs, ES6 introduced Set (a collection of unique values with average lookup via .has()) and Map (an ordered key-value dictionary allowing arbitrary key types including objects and numbers, with direct .size tracking). Unlike plain objects, Map never suffers from prototype key collisions (such as toString or constructor) and preserves insertion order reliably.
function checkPasswordStrength(pwd) {
const rules = [
{ label: "Minimum 8 characters", valid: pwd.length >= 8 },
{ label: "Contains uppercase letter", valid: /[A-Z]/.test(pwd) },
{ label: "Contains digit", valid: /\d/.test(pwd) },
{ label: "Contains special symbol", valid: /[!@#$%^&*]/.test(pwd) }
];
return rules.filter((r) => !r.valid).map((r) => r.label);
}
// Using Set to store unique selected skills without duplicates
const selectedSkills = new Set(["JavaScript", "HTML5"]);
selectedSkills.add("React");
selectedSkills.add("JavaScript"); // Ignored automatically
console.log("Unique skills:", Array.from(selectedSkills));
console.log("Missing rules:", checkPasswordStrength("web2026"));6.3 Optional Chaining, Nullish Coalescing, and Safe Object Traversal
When processing nested JSON payloads from external APIs or complex form models, attempting to read a deeply nested property such as student.guardian.contact.phone throws a TypeError if any intermediate object is null or missing. Modern JavaScript solves this concisely with the optional chaining operator (?.) and nullish coalescing operator (??). Evaluating student?.guardian?.contact?.phone ?? "Not Provided" short-circuits safely to the fallback string without verbose nested if guards.
Similarly, combining Object.entries() with Array.prototype.reduce() allows transforming arrays of form fields or API records into indexed lookup dictionaries in a single immutable pass, avoiding nested loops and reducing time complexity from to during UI rendering.
const records = [
{ id: "S101", name: "Meera", meta: { hostel: "Block B" } },
{ id: "S102", name: "Arjun", meta: null }
];
const directory = records.reduce((map, student) => {
const hostel = student?.meta?.hostel ?? "Day Scholar";
map[student.id] = { name: student.name, hostel };
return map;
}, {});
console.log(directory["S101"], directory["S102"]);Module III: React JS: Introduction
Chapter 1: Introduction to React JS, Architecture, and Virtual DOM
1.1 Need for React JS and Modern UI Challenges
As web applications grew from static multi-page documents into rich Single Page Applications (SPAs), direct imperative manipulation of the browser Document Object Model (DOM) using vanilla JavaScript or jQuery became error-prone and slow. In traditional imperative programming, developers manually locate DOM nodes, mutate attributes, attach listeners, and synchronize UI state across dozens of views. Frequent unbatched DOM writes trigger expensive browser layout recalculations (reflows) and repaints.
Developed by Jordan Walke at Facebook (Meta) and open-sourced in 2013, React JS is a declarative, component-based JavaScript library for building user interfaces. Instead of writing step-by-step DOM mutation commands, developers describe what the UI should look like for a given application state, and React automatically determines the minimal DOM updates required when state changes.
1.2 Applications and Core Features of React
React powers large-scale production web applications (dashboards, e-commerce platforms, social networks, collaborative editors), cross-platform native mobile applications via React Native, and server-rendered or statically generated applications via frameworks such as Next.js. Its defining features include:
- Declarative UI: Views are pure projections of current state, making UI behavior predictable and easier to debug.
- Component-Based Architecture: Complex interfaces are decomposed into small, isolated, reusable building blocks that encapsulate markup, logic, and styling.
- JSX (JavaScript XML): Allows writing HTML-like declarative syntax directly inside JavaScript modules.
- Virtual DOM and Reconciliation: Minimizes costly real DOM mutations by diffing lightweight in-memory UI trees.
- Unidirectional Data Flow: Data flows strictly top-down from parent components to child components via props, simplifying state tracing.
1.3 React Architecture and the Virtual DOM
The Virtual DOM (VDOM) is a lightweight, in-memory JavaScript object representation of the actual browser DOM. Manipulating plain JavaScript objects in memory is orders of magnitude faster than mutating real browser DOM nodes. React's rendering pipeline operates in three stages:
- Render Phase: When state or props update, React invokes the component functions to generate a new Virtual DOM tree of React elements.
- Reconciliation (Diffing): React compares the new Virtual DOM tree against the previous snapshot using an heuristic diffing algorithm. Two key assumptions power this speed: elements of different types (e.g.,
<div>vs<span>) produce different trees, and sibling elements in lists are matched across renders using stablekeyprops. - Commit Phase: React batches only the minimal, exact differences (patches) and applies them to the real browser DOM in a single synchronized pass. Modern React (v16+) uses the Fiber architecture, which splits rendering work into interruptible units so high-priority user interactions remain responsive.
| Aspect | Real Browser DOM | React Virtual DOM |
|---|---|---|
| Representation | Heavy native C++ browser tree of nodes | Lightweight plain JavaScript objects in memory |
| Update Cost | High; triggers CSS style recalc, reflow, repaint | Very low; object creation and comparison in JS heap |
| Update Strategy | Direct imperative mutation | Batched declarative diffing and minimal patching |
Chapter 2: Setting Up the React Development Environment
2.1 Node.js, npm, and Toolchain Prerequisites
Although React runs in the browser, modern React development relies on Node.js on the developer's machine to run build tools, bundlers, transpilers (such as Babel), and local development servers. Node.js is a cross-platform JavaScript runtime built on Chrome's V8 engine. Installing Node.js automatically installs npm (Node Package Manager), the command-line tool and registry used to install third-party libraries (react, react-dom, react-router-dom) and manage project scripts.
Every Node-based React project contains a package.json manifest file recording project metadata, dependency version ranges, and executable scripts (start, build, test), alongside a package-lock.json file that locks exact dependency versions for reproducible builds across machines.
2.2 Scaffolding with Create React App (CRA)
Create React App (CRA) is the classic official CLI tool that sets up a zero-configuration React environment preconfigured with Webpack, Babel (to transpile JSX and ES6+ syntax into browser-compatible JavaScript), ESLint, and Jest. Using npx runs the latest package without polluting global installations.
# Verify Node.js and npm versions node -v npm -v # Scaffold a new React project npx create-react-app modern-web-app # Navigate into the project and start the dev server cd modern-web-app npm start
A generated CRA workspace follows a standard directory layout: public/index.html hosts the single root container <div id="root"></div>; src/index.js serves as the JavaScript entry point that mounts the React tree into #root; and src/App.js defines the top-level root component. Running npm run build compiles, minifies, and bundles assets into a production-ready build/ folder.
Chapter 3: JSX Syntax and Conditional Rendering
3.1 JSX Syntax Rules and Transpilation
JSX (JavaScript XML) is a syntax extension for JavaScript that allows developers to write markup-like UI structures inside .js or .jsx files. Browsers do not execute JSX natively; during the build step, Babel compiles every JSX tag into React.createElement(type, props, ...children) calls (or the modern _jsx() runtime transform), which return plain React element objects.
Writing valid JSX requires adhering to strict syntactic rules that differ slightly from standard HTML:
- Single Root Element: A component must return a single top-level parent node. Multiple sibling elements must be wrapped in a parent
<div>or aReact.Fragment(shorthand<>...</>), which groups children without adding extra DOM nodes. - Explicit Tag Closing: Every tag must be closed, including void HTML tags such as
<img src="..." alt="..." />,<input />, and<br />. - camelCase Attributes: HTML attributes that conflict with JavaScript reserved keywords or use hyphens become camelCase:
classbecomesclassName,forbecomeshtmlFor,tabindexbecomestabIndex, and event attributes becomeonClick,onChange. - Expressions in JSX: Curly braces
{ ... }embed any valid JavaScript expression—variables, arithmetic, function calls, array.map()results—directly inside JSX. Imperative statements such asiforforcannot appear directly inside curly braces.
function CourseBanner() {
const course = "Modern Web Technologies";
const credits = 4;
return (
<>
<h1 className="banner-title">{course.toUpperCase()}</h1>
<p htmlFor="credit-info">Total Credits: {credits} ({credits >= 4 ? "Core" : "Elective"})</p>
</>
);
}3.2 Conditional Rendering Techniques in JSX
Components frequently render different UI based on authentication status, loading state, or data availability. React supports three idiomatic conditional rendering patterns:
- if/else with Element Variables: Use standard JavaScript
if/elseoutside the JSX return statement to assign JSX to a variable or return early. Ideal for complex multi-branch layouts. - Ternary Operator (
condition ? exprA : exprB): Evaluates inline inside JSX curly braces when choosing between two alternative elements or values. - Logical AND (
condition && <Component />): Short-circuits inline to render an element only when the condition is truthy. Caution: always coerce numeric conditions to booleans (e.g.,items.length > 0 && ...) because a falsy0on the left side renders the literal digit0on screen.
function StudentDashboard({ isLoggedIn, notifications }) {
// 1. Early return / element variable with if-else
if (!isLoggedIn) {
return <p className="alert">Please sign in to access course notes.</p>;
}
let statusBadge;
if (notifications.length > 5) {
statusBadge = <span>High Activity</span>;
} else {
statusBadge = <span>Normal Activity</span>;
}
return (
<div>
{statusBadge}
{/* 2. Ternary operator */}
<h2>{notifications.length > 0 ? "Unread Alerts" : "All Caught Up"}</h2>
{/* 3. Logical && operator with explicit boolean check */}
{notifications.length > 0 && (
<ul>
{notifications.map((note, idx) => <li key={idx}>{note}</li>)}
</ul>
)}
</div>
);
}Chapter 4: Components, Elements, and Props
4.1 Creating and Rendering React Components
In React 18, an application mounts to the browser DOM through ReactDOM.createRoot(container).render(<App />). Every user-defined React component name must begin with an uppercase letter (PascalCase, such as <Header />); lowercase names like <div> or <span> are treated by JSX as built-in HTML host tags.
4.2 Components vs Elements and Built-In Components
A React Element is a plain, immutable JavaScript object describing what should appear on screen (for example, { type: 'h1', props: { children: 'Hello' } }). Creating elements is cheap, and once created, their properties cannot be modified. A React Component, by contrast, is a reusable function or class that accepts input (props) and returns a tree of React elements. React also provides built-in components such as HTML host elements (<button>, <input>), <React.Fragment>, and <React.StrictMode> (which activates extra development-time checks).
4.3 Attributes vs Props, Function Components, and Passing Props
In HTML, attributes are string-only key-value pairs parsed from markup to initialize DOM properties. In React, props (short for properties) are arbitrary JavaScript inputs—strings, numbers, booleans, arrays, objects, functions, or even other JSX elements—passed from a parent component to a child component. Unlike HTML attributes, props are strictly read-only (immutable) inside the receiving child component: a component must behave like a pure function with respect to its props and never mutate them.
Function components are standard JavaScript functions that accept a single props object parameter (commonly destructured directly in the parameter list) and return JSX. Special prop props.children automatically captures whatever nested JSX is placed between a component's opening and closing tags.
function Card({ title, children }) {
return (
<section className="card">
<h3>{title}</h3>
<div>{children}</div>
</section>
);
}
function CourseCard({ code, title, credits = 4 }) {
return (
<Card title={code + " - " + title}>
<p>Course Credits: {credits}</p>
</Card>
);
}
export default function App() {
return (
<main>
<CourseCard code="UK2DSCCAP105" title="Modern Web Technologies" credits={4} />
</main>
);
}Chapter 5: Reconciliation, Lists, Keys, and Component Composition
5.1 Reconciliation, Keys in Lists, and React Fiber
When rendering arrays of data in JSX using Array.prototype.map(), React requires a unique, stable key prop on each sibling element returned by the callback. Keys act as persistent identity hints across re-renders so React's diffing algorithm can tell whether an item was reordered, inserted, or deleted. Using an array index (key={index}) is strongly discouraged whenever items can be added, removed, or sorted, because indices shift and cause React to misassociate component state or input focus with the wrong data item. Always use a stable unique identifier such as a database ID or course code (key={course.code}).
Under the hood, React's Fiber architecture represents each component instance and DOM node as a linked-list Fiber node containing component type, pending props, state hooks, and effect flags. By breaking reconciliation work into small incremental units, Fiber enables React to pause low-priority background rendering, yield to the browser for urgent user input (such as typing or clicking), and resume work without dropping frames.
5.2 Anatomy of a React Project and Build Toolchain
A standard Create React App project organizes source files cleanly so Webpack and Babel can bundle them for production:
| File / Directory | Role in React Application |
|---|---|
package.json |
Declares dependencies (react, react-dom, react-scripts) and CLI scripts. |
public/index.html |
Single HTML shell containing <div id="root"></div> where React mounts. |
src/index.js |
Entry point calling ReactDOM.createRoot(...).render(<App />). |
src/App.js |
Root component composing layout, navigation, and feature subcomponents. |
node_modules/ |
Installed npm packages; excluded from version control via .gitignore. |
ES Modules (export default and named export { ... } paired with import) allow splitting every component into its own focused file. During development, npm start launches a local server with Hot Module Replacement (HMR) so code edits reflect immediately in the browser without losing state. For deployment, npm run build tree-shakes unused exports, minifies JavaScript and CSS, and hashes filenames for optimal browser caching.
5.3 JSX Security (XSS Protection) and Dynamic List Rendering
A major built-in security advantage of JSX is automatic content escaping: any string interpolated inside {userInput} is escaped by React DOM before insertion, neutralizing Cross-Site Scripting (XSS) injection attacks by default. Furthermore, JSX seamlessly combines array filter() and map() chains to render dynamic, data-driven interfaces.
5.4 Component Composition and Multi-Component Architecture
Rather than relying on class inheritance, React favors component composition—building specialized components by wrapping or combining smaller generic components via props and props.children. When multiple sibling components need access to shared data, state is placed in their closest common ancestor and passed downward as props (a pattern known as lifting state up).
function StatusPill({ active }) {
return (
<span className={active ? "pill-active" : "pill-inactive"}>
{active ? "Active" : "Archived"}
</span>
);
}
function CourseRow({ course }) {
return (
<li>
<strong>{course.code}</strong>: {course.title} ({course.credits} Credits){" "}
<StatusPill active={course.active} />
</li>
);
}
function CourseDirectory({ courses, onlyActive }) {
const visibleCourses = onlyActive
? courses.filter((c) => c.active)
: courses;
if (visibleCourses.length === 0) {
return <p>No matching courses found.</p>;
}
return (
<ul>
{visibleCourses.map((course) => (
<CourseRow key={course.code} course={course} />
))}
</ul>
);
}
export default function SemesterPortal() {
const catalog = [
{ code: "UK2DSCCAP105", title: "Modern Web Technologies", credits: 4, active: true },
{ code: "UK2DSCCAP104", title: "Data Structures", credits: 4, active: true },
{ code: "UK1DSCCAP101", title: "Problem Solving in C", credits: 4, active: false }
];
return (
<section>
<h2>BCA Semester II Course Directory</h2>
<CourseDirectory courses={catalog} onlyActive={true} />
</section>
);
}Chapter 6: Declarative Thinking, Pure Components, and React Best Practices
6.1 Thinking in React: Step-by-Step UI Decomposition
Building maintainable React applications follows a disciplined five-step engineering workflow:
- Break the UI into a Component Hierarchy: Draw boundaries around every visual unit that has a single responsibility (Single Responsibility Principle)—such as a search bar, filter toggle, data table, and individual row.
- Build a Static Version First: Assemble the component tree using props only, without interactivity or state, to verify layout structure and data flow.
- Identify Minimal UI State: Determine which values change over time and cannot be computed from existing props or state (avoid redundant derived state).
- Identify Where State Should Live: Place state in the lowest common parent component shared by all components that read or update it.
- Add Inverse Data Flow: Pass callback functions down as props so child components can notify parent components when user actions occur.
6.2 Pure Components, Immutability, and StrictMode
React assumes every function component is pure with respect to its rendering logic: given identical props and state, it must return identical JSX without mutating external variables, DOM nodes, or incoming prop objects during render. Wrapping the root application in <React.StrictMode> during development intentionally double-invokes component functions and effects to surface accidental side effects or impure mutations early before production deployment.
| Concept | Imperative Approach (Vanilla JS) | Declarative Approach (React JS) |
|---|---|---|
| DOM Updates | Manually query nodes and call appendChild / textContent |
Describe target UI in JSX; React diffs Virtual DOM and commits patches |
| UI Consistency | Developer must synchronize all dependent DOM nodes manually | UI is always a deterministic function of current props and state |
| Code Reuse | HTML templates plus separate global JS event scripts | Self-contained reusable components encapsulating markup and logic |
| List Rendering | Manual loop creating elements and managing node removal | array.map() with stable key props for automatic reconciliation |
6.3 Worked Multi-Component Case Study: Interactive Study Tracker
The following example demonstrates JSX conditional rendering (ternary and &&), element variables, props destructuring, props.children, list keys, and clean component composition working together in a cohesive React module.
function Panel({ heading, children }) {
return (
<div className="panel">
<h3>{heading}</h3>
<div className="panel-body">{children}</div>
</div>
);
}
function ModuleBadge({ completed }) {
return (
<span className={completed ? "badge-done" : "badge-pending"}>
{completed ? "Completed" : "In Progress"}
</span>
);
}
function ModuleItem({ mod }) {
return (
<li className="module-row">
<span>Module {mod.num}: {mod.topic}</span>{" "}
<ModuleBadge completed={mod.done} />
{mod.hours >= 15 && <small> (Core Credit Unit)</small>}
</li>
);
}
export default function SyllabusTracker({ modules, studentName }) {
const completedCount = modules.filter((m) => m.done).length;
let progressMessage;
if (completedCount === modules.length) {
progressMessage = "All syllabus modules completed!";
} else {
progressMessage = completedCount + " of " + modules.length + " modules finished.";
}
return (
<Panel heading={"Study Progress: " + studentName}>
<p>{progressMessage}</p>
{modules.length > 0 ? (
<ul>
{modules.map((m) => (
<ModuleItem key={m.num} mod={m} />
))}
</ul>
) : (
<p>No modules assigned for this semester.</p>
)}
</Panel>
);
}Chapter 7: Practical JSX Patterns, PropTypes, and Debugging React Apps
7.1 Common JSX Pitfalls and Clean Refactoring Patterns
Developers transitioning from HTML to JSX frequently encounter subtle syntax and runtime pitfalls. First, because JavaScript objects use curly braces {...}, passing an inline style object in JSX requires double braces: style={{ color: '#1F3A5F', fontWeight: 'bold' }}, where the outer braces denote a JSX expression and the inner braces denote a JavaScript object literal. Second, HTML comments (<!-- ... -->) are invalid inside JSX; comments must be written inside curly braces as JavaScript block comments: {/* Comment text */}.
Third, boolean props default to true when passed without a value (for example, <Button disabled /> is equivalent to <Button disabled={true} />). Fourth, spreading props onto a DOM element (<input {...restProps} />) is convenient for reusable wrapper components, provided non-DOM custom props are destructured out beforehand so React does not emit unknown-attribute warnings in the browser console.
7.2 Inspecting Component Trees with React Developer Tools
The React Developer Tools browser extension adds two specialized panels to Chrome and Firefox DevTools: Components and Profiler. The Components tab displays the live hierarchical React component tree (rather than raw DOM nodes), allowing developers to inspect current props, hooks state, and parent-child ownership in real time. The Profiler records render durations and highlights which components re-rendered and why, helping teams eliminate unnecessary renders before deploying to production.
function AlertBanner({ variant = "info", dismissible = false, onClose, children }) {
const palette = {
info: { borderLeft: "3px solid #1F3A5F", padding: "8px 12px" },
warning: { borderLeft: "3px solid #B45309", padding: "8px 12px" }
};
return (
<div role="alert" style={palette[variant] || palette.info}>
{/* Render body passed via props.children */}
<div>{children}</div>
{dismissible && (
<button type="button" onClick={onClose}>
Dismiss
</button>
)}
</div>
);
}7.3 Static Type Checking Awareness and Component Documentation
As React codebases expand across multiple teams, documenting expected prop shapes prevents runtime mismatches where a parent passes a string instead of a number or omits a required callback. Historically, React teams used the prop-types package for runtime prop validation in development mode (for example, validating that credits is a number and title is a required string). In modern engineering workflows, teams increasingly pair React with TypeScript or JSDoc annotations to catch prop contract violations directly inside the code editor before the application even runs in a browser.
Regardless of tooling, writing clear, self-documenting component interfaces—using explicit destructured parameter names, sensible default parameter values, and single-purpose component boundaries—ensures that every UI building block remains predictable, testable, and easy to refactor throughout the lifecycle of the web application.
Module IV: React JS: Events, Styles, Forms in React JS
Chapter 1: Component State, Lifecycle Methods, and React Hooks
1.1 Understanding Component State vs Props
While props carry read-only configuration from parent to child, state represents private, mutable data owned and managed internally by a component that changes over time—such as form input text, toggle flags, fetched API records, or active tab indices. Whenever a component's state changes, React automatically schedules a re-render of that component and its subtree to keep the UI synchronized.
| Criterion | Props | State |
|---|---|---|
| Ownership | Passed down from parent component | Owned and initialized inside the component |
| Mutability | Immutable (read-only inside child) | Mutable via setState() or Hook setter |
| Purpose | Configure and parameterize components | Track dynamic interactive data over time |
1.2 Managing State with setState() and Lifecycle Methods (Class Components)
In class-based React components (which extend React.Component), state is initialized as an object on this.state inside the constructor and updated exclusively via this.setState(). Direct mutation (such as this.state.count = 1) never triggers a re-render. Calling setState() performs a shallow merge of the provided keys into this.state and may be batched asynchronously by React for performance. When a new state depends on the previous state, developers pass an updater callback: this.setState((prev) => ({ count: prev.count + 1 })).
Class components follow a three-phase Component Lifecycle:
- Mounting Phase: Instance creation and initial DOM insertion—
constructor(),static getDerivedStateFromProps(),render(), andcomponentDidMount()(ideal for initial API fetches, timers, or DOM subscriptions). - Updating Phase: Triggered by new props or
setState()—shouldComponentUpdate()(performance optimization),render(),getSnapshotBeforeUpdate(), andcomponentDidUpdate(prevProps, prevState). - Unmounting Phase: Cleanup right before the component is removed from the DOM—
componentWillUnmount()(used to clear intervals, abort pending network requests, and remove global event listeners to prevent memory leaks).
1.3 React Hooks in Function Components
Introduced in React 16.8, Hooks allow function components to use state, lifecycle side effects, refs, and context without writing classes. Two Rules of Hooks apply universally: (1) call Hooks only at the top level of a function component (never inside loops, conditions, or nested functions), and (2) call Hooks only from React function components or custom Hooks.
useState(initialValue): Returns a pair[state, setState]. Unlike classsetState, auseStatesetter replaces the value rather than merging objects, so object updates use spread syntax (setUser(prev => ({ ...prev, name: 'Anu' }))).useEffect(effectFn, deps): Synchronizes a component with external systems (API calls, timers, document title). An empty dependency array[]runs once on mount (likecomponentDidMount); specifying dependencies[id]re-runs wheneveridchanges; returning a cleanup function fromeffectFnruns before the next effect and on unmount (likecomponentWillUnmount).useRef(initialValue): Returns a mutable{ current }container persisting across renders without triggering re-renders—used for accessing DOM nodes directly or storing timer IDs.
import { useState, useEffect } from "react";
function LiveClock() {
const [seconds, setSeconds] = useState(0);
const [running, setRunning] = useState(true);
useEffect(() => {
if (!running) return;
const timerId = setInterval(() => {
setSeconds((prev) => prev + 1);
}, 1000);
// Cleanup function (equivalent to componentWillUnmount)
return () => clearInterval(timerId);
}, [running]);
return (
<div>
<p>Elapsed Seconds: {seconds}</p>
<button onClick={() => setRunning((r) => !r)}>
{running ? "Pause" : "Resume"}
</button>
</div>
);
}Chapter 2: Event Handling in React
2.1 SyntheticEvent and Event Handler Functions
React wraps native browser events inside a cross-browser SyntheticEvent object that provides a consistent API (event.target, event.preventDefault(), event.stopPropagation()) across all browsers. React event props use camelCase (onClick, onChange, onSubmit, onKeyDown) and accept a function reference rather than a string. A common mistake is invoking the handler immediately during render (onClick={handleClick()}) instead of passing the reference (onClick={handleClick}) or wrapping parameterized calls in an arrow function (onClick={() => handleDelete(item.id)}).
2.2 Binding Event Handler Functions
In JavaScript, class methods are not bound to the class instance by default. When a class method is passed as a callback to onClick={this.handleClick}, invoking it later causes this inside the method to lose its instance binding. Developers solve this in three ways: (1) binding in the constructor (this.handleClick = this.handleClick.bind(this)—most efficient), (2) defining the handler as a class field arrow function (handleClick = () => { ... }—modern class idiom), or (3) wrapping in an inline arrow function in JSX (onClick={() => this.handleClick()}). Function components avoid this binding entirely because handlers are closures.
import React from "react";
class ClassCounter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
// Explicit binding in constructor
this.increment = this.increment.bind(this);
}
increment() {
this.setState((prev) => ({ count: prev.count + 1 }));
}
// Class field arrow function (auto-bound lexically)
reset = () => {
this.setState({ count: 0 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>+1</button>
<button onClick={this.reset}>Reset</button>
</div>
);
}
}Chapter 3: Controlled vs Uncontrolled Forms in React
3.1 Controlled Components
In a controlled component, React state serves as the single source of truth for form input values. The input receives its current value via the value (or checked for checkboxes) prop and notifies React of every keystroke through an onChange handler, which updates state. Controlled inputs enable instant field-level validation, conditional disabling of submit buttons, and input formatting.
3.2 Uncontrolled Components and Form Submission
In an uncontrolled component, the browser DOM retains the input's internal value, and React reads it on demand (typically during submission) using a ref created with useRef() or React.createRef(). Initial values are supplied with defaultValue rather than value. Uncontrolled inputs are essential for <input type="file" />, whose value is read-only for security reasons. Regardless of approach, form submission is handled via onSubmit on the <form> element, calling event.preventDefault() to prevent a full-page browser reload.
import { useState } from "react";
function EnrollmentForm() {
const [formData, setFormData] = useState({ name: "", email: "", agree: false });
const [status, setStatus] = useState("");
function handleChange(event) {
const { name, value, type, checked } = event.target;
setFormData((prev) => ({
...prev,
[name]: type === "checkbox" ? checked : value
}));
}
function handleSubmit(event) {
event.preventDefault();
if (!formData.name.trim() || !formData.agree) {
setStatus("Please enter your name and accept terms.");
return;
}
setStatus("Submitted for " + formData.name);
}
return (
<form onSubmit={handleSubmit}>
<input name="name" value={formData.name} onChange={handleChange} placeholder="Full Name" />
<input name="email" type="email" value={formData.email} onChange={handleChange} placeholder="Email" />
<label>
<input name="agree" type="checkbox" checked={formData.agree} onChange={handleChange} />
Accept Syllabus Guidelines
</label>
<button type="submit">Register</button>
{status && <p>{status}</p>}
</form>
);
}Chapter 4: Styling Approaches and UI Frameworks in React
4.1 Core Styling Approaches: CSS, Inline Styles, CSS Modules, and CSS-in-JS
React does not prescribe a single styling mechanism, giving teams flexibility to choose based on project scale and maintainability needs:
| Approach | Scoping | Dynamic Styling | Key Characteristics |
|---|---|---|---|
| Regular CSS Stylesheets | Global | Via conditional className |
Imported via import './App.css'; simple, familiar, but prone to class name collisions. |
| Inline Styles | Component-local | Direct JS expressions | Passed as camelCase JS object style={{ color: 'navy' }}; lacks pseudo-classes and media queries. |
| CSS Modules | Locally scoped | Conditional class composition | Files named *.module.css auto-generate unique hashed class names, preventing collisions. |
| CSS-in-JS | Component-scoped | Props-driven template literals | Libraries like styled-components and Emotion bind styles directly to components with full CSS support. |
// 1. Inline style object
const badgeStyle = { backgroundColor: "#1F3A5F", color: "#FFFFFF", padding: "4px 10px" };
// 2. CSS Module usage (assuming Button.module.css defines .primaryBtn)
// import styles from "./Button.module.css";
// <button className={styles.primaryBtn}>Save</button>
// 3. CSS-in-JS using styled-components
// import styled from "styled-components";
// const ActionButton = styled.button`
// background: ${(props) => (props.primary ? "#1F3A5F" : "#E5E5E5")};
// color: ${(props) => (props.primary ? "#FFF" : "#111")};
// padding: 8px 16px;
// `;4.2 Popular Styling Libraries: Bootstrap and Material-UI (MUI)
To accelerate responsive UI delivery, React applications frequently adopt component styling libraries:
- Bootstrap (and React-Bootstrap): Provides a battle-tested 12-column responsive flexbox grid system, utility classes, and accessible UI widgets. While standard Bootstrap relies on CSS classes,
react-bootstrapreplaces Bootstrap's jQuery dependency with pure React components such as<Container>,<Row>,<Col>,<Navbar>, and<Modal>. - Material-UI (MUI): Implements Google's Material Design specification as a comprehensive React component library. MUI features a
ThemeProviderfor global typography and color palettes, an Emotion-poweredsxprop for rapid responsive overrides, and rich interactive components including<Button>,<TextField>,<Card>,<DataGrid>, and<AppBar>.
Chapter 5: Deep Dive into Hooks, Uncontrolled Refs, and UI Framework Integration
5.1 Advanced Hook Patterns: useContext, useRef, and Custom Hooks
Beyond useState and useEffect, React provides built-in Hooks for solving architectural challenges cleanly:
useContext(MyContext): Reads values from a React Context provider without passing props manually through intermediate components (eliminating prop drilling for themes, authenticated user profiles, or locale settings).useRef(initialValue): Stores mutable references across renders without triggering re-renders—essential for imperative DOM operations such as focusing an input field on mount (inputRef.current.focus()) or reading uncontrolled form fields.- Custom Hooks: Reusable JavaScript functions whose names begin with
use(e.g.,useFetch,useFormInput) that compose built-in Hooks to share stateful logic across multiple components without duplicating code.
When performing asynchronous data fetching inside useEffect, always guard against race conditions and memory leaks by using an AbortController inside the cleanup function so stale requests are cancelled if the component unmounts or dependencies change before the response arrives.
import { useState, useEffect, useRef } from "react";
function useCourseSearch(query) {
const [results, setResults] = useState([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
if (!query.trim()) {
setResults([]);
return;
}
const controller = new AbortController();
setLoading(true);
fetch("/api/courses?q=" + encodeURIComponent(query), { signal: controller.signal })
.then((res) => res.json())
.then((data) => {
setResults(data);
setLoading(false);
})
.catch((err) => {
if (err.name !== "AbortError") setLoading(false);
});
return () => controller.abort();
}, [query]);
return { results, loading };
}
function SearchBox() {
const [term, setTerm] = useState("");
const inputRef = useRef(null);
const { results, loading } = useCourseSearch(term);
useEffect(() => {
inputRef.current?.focus();
}, []);
return (
<div>
<input ref={inputRef} value={term} onChange={(e) => setTerm(e.target.value)} placeholder="Search..." />
{loading && <p>Loading...</p>}
<ul>{results.map((r) => <li key={r.id}>{r.title}</li>)}</ul>
</div>
);
}5.2 Controlled vs Uncontrolled Forms Comparison
Selecting between controlled and uncontrolled inputs depends on whether the UI requires instant validation and dynamic field synchronization or simple one-time submission reads:
| Feature | Controlled Component | Uncontrolled Component |
|---|---|---|
| Source of Truth | React component state | Browser DOM element |
| Value Prop | value={state} + onChange |
defaultValue="initial" + ref |
| Instant Validation | Yes, on every keystroke | Typically validated on submit |
| File Inputs | Not supported (browser security) | Required for <input type="file" /> |
5.3 Theming and Responsive Layout with Material-UI and React-Bootstrap
UI component libraries standardize accessibility (ARIA attributes, keyboard navigation), responsive breakpoints, and visual consistency across teams. Below is a comparison of how a responsive action card is authored using Material-UI's ThemeProvider and sx prop.
import { ThemeProvider, createTheme, Card, CardContent, Typography, Button } from "@mui/material";
const universityTheme = createTheme({
palette: {
primary: { main: "#1F3A5F" },
secondary: { main: "#42526E" }
}
});
export default function MuiCourseBanner() {
return (
<ThemeProvider theme={universityTheme}>
<Card sx={{ maxWidth: 420, margin: "16px auto", padding: 1 }}>
<CardContent>
<Typography variant="h6" color="primary">
UK2DSCCAP105: Modern Web Technologies
</Typography>
<Typography variant="body2" sx={{ marginBottom: 2 }}>
BCA Semester II • React Components, Hooks, and Styling
</Typography>
<Button variant="contained" color="primary" onClick={() => console.log("Enrolled")}>
Open Module
</Button>
</CardContent>
</Card>
</ThemeProvider>
);
}Chapter 6: React Event Architecture, Bootstrap Grids, and Form Validation
6.1 SyntheticEvent Internals and Performance Optimization
React implements event delegation at the root container (#root in React 18) rather than attaching individual DOM listeners to every button or input element. When a user clicks a deeply nested element, the browser bubbles the event to the root container, where React constructs a normalized SyntheticEvent and dispatches it through the React component tree. This architecture drastically reduces memory overhead in large tables and lists.
When handling high-frequency events such as onChange on a search input or onMouseMove, wrapping expensive computations in a debounce timer inside useEffect prevents redundant API requests on every keystroke. Below is a summary of commonly used React SyntheticEvent properties and handler patterns.
| React Event Prop | Trigger Condition | Commonly Accessed Properties |
|---|---|---|
onClick |
Primary click or Enter/Space on button | e.currentTarget, e.shiftKey, e.stopPropagation() |
onChange |
Value change on input, select, textarea, checkbox | e.target.name, e.target.value, e.target.checked |
onSubmit |
Form submission via button or Enter key | e.preventDefault() to stop browser page reload |
onKeyDown |
Any key pressed while element is focused | e.key, e.code, e.ctrlKey, e.preventDefault() |
onFocus / onBlur |
Element gains or loses keyboard focus | e.relatedTarget for focus transition tracking |
6.2 Responsive Layout with React-Bootstrap
React-Bootstrap translates Bootstrap's 12-column responsive grid and utility classes into declarative JSX components without any jQuery dependency. Breakpoint props (xs, sm, md, lg, xl) allow columns to stack vertically on mobile phones and align side-by-side on desktop monitors automatically.
import { useState } from "react";
import { Container, Row, Col, Form, Button, Alert } from "react-bootstrap";
export default function FeedbackPortal() {
const [topic, setTopic] = useState("hooks");
const [comments, setComments] = useState("");
const [submitted, setSubmitted] = useState(false);
function handleSubmit(e) {
e.preventDefault();
if (comments.trim().length < 10) return;
setSubmitted(true);
}
return (
<Container className="py-4">
<Row className="justify-content-center">
<Col xs={12} md={8} lg={6}>
<h3>Course Module Feedback</h3>
{submitted && <Alert variant="success">Thank you for your feedback!</Alert>}
<Form onSubmit={handleSubmit}>
<Form.Group className="mb-3">
<Form.Label>Select Module Topic</Form.Label>
<Form.Select value={topic} onChange={(e) => setTopic(e.target.value)}>
<option value="hooks">React Hooks & Lifecycle</option>
<option value="forms">Controlled vs Uncontrolled Forms</option>
<option value="styling">CSS Modules & Material-UI</option>
</Form.Select>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Comments (min 10 chars)</Form.Label>
<Form.Control
as="textarea"
rows={3}
value={comments}
onChange={(e) => setComments(e.target.value)}
/>
</Form.Group>
<Button type="submit" variant="primary" disabled={comments.trim().length < 10}>
Submit Feedback
</Button>
</Form>
</Col>
</Row>
</Container>
);
}6.3 Class Component Lifecycle Reference Summary
Although modern projects favor function components with Hooks, maintaining legacy React codebases requires fluency in class lifecycle methods. componentDidMount runs once after initial DOM insertion; componentDidUpdate(prevProps, prevState) runs after every re-render (always guard setState inside an if condition comparing previous vs current props/state to avoid infinite update loops); and componentWillUnmount tears down subscriptions and timers cleanly.
Chapter 7: CSS Modules Architecture and Dynamic State-Driven Styling
7.1 Preventing Style Collisions with CSS Modules
In large multi-developer React codebases, global CSS files inevitably suffer from selector name collisions—for example, two different modules defining .card-header with conflicting margins or colors. CSS Modules solve this at build time: any stylesheet named ComponentName.module.css is compiled by Webpack or Vite so that every class selector is transformed into a globally unique hashed identifier (such as Card_header__x8K2p). Developers import the style map as a JavaScript object and apply classes cleanly via className={styles.header}.
When combining multiple conditional classes—such as an active state alongside a base button class—template literals or utility helpers like clsx keep JSX readable without cluttering markup.
/* CourseCard.module.css:
.card { border: 1px solid #dfe1e6; padding: 12px; margin-bottom: 10px; }
.selected { border-color: #1F3A5F; font-weight: 700; }
*/
import { useState } from "react";
import styles from "./CourseCard.module.css";
export default function SelectableCourse({ code, title }) {
const [isSelected, setIsSelected] = useState(false);
const cardClass = isSelected
? styles.card + " " + styles.selected
: styles.card;
return (
<div className={cardClass} onClick={() => setIsSelected((prev) => !prev)}>
<span>{code}: {title}</span>
<span>{isSelected ? " [Selected]" : " [Click to Select]"}</span>
</div>
);
}7.2 Choosing the Right Styling Strategy for Production Teams
When selecting a styling approach for a new React project, engineering teams weigh bundle size, runtime overhead, and design-system consistency. CSS Modules offer zero runtime cost and full CSS feature support (pseudo-selectors, media queries, animations). CSS-in-JS libraries like styled-components excel when component styling depends heavily on dynamic JavaScript props, though they incur a small runtime style-injection cost. UI frameworks such as Material-UI and React-Bootstrap dramatically accelerate internal dashboards and enterprise portals by providing accessible, pre-tested components out of the box.
Module V: Flexi Module: Cookies in JavaScript & React Router
Chapter 1: Cookies in JavaScript and Client-Side Persistence
1.1 HTTP Statelessness and the Role of Cookies
The Hypertext Transfer Protocol (HTTP) is inherently stateless: each request from a browser to a server is independent and carries no built-in memory of prior requests. To maintain user sessions, shopping carts, language preferences, and personalization across page loads, browsers support HTTP cookies—small key-value text records (typically capped at approximately 4 KB per cookie) stored by the browser and automatically attached to subsequent HTTP requests to the matching origin.
Cookies fall into two lifetime categories: session cookies, which omit an expiration attribute and are automatically purged when the browser closes, and persistent cookies, which include an explicit expires UTC date or max-age duration in seconds and survive browser restarts.
1.2 Managing Cookies with document.cookie
In client-side JavaScript, cookies are accessed and mutated through the document.cookie property. Despite looking like a normal string, document.cookie behaves as an accessor: assigning a formatted string appends or updates a single named cookie without overwriting other existing cookies, whereas reading document.cookie returns a single semicolon-separated string of all non-HttpOnly cookies accessible to the current path and domain.
Cookie values should always be encoded with encodeURIComponent() when writing and decoded with decodeURIComponent() when reading so that spaces, semicolons, or special characters do not corrupt cookie parsing. Deleting a cookie requires overwriting it with the same name and path while setting max-age=0 or an expires timestamp in the past.
| Cookie Attribute | Purpose and Behavior |
|---|---|
expires=<UTC-date> |
Sets an absolute GMT/UTC expiration timestamp for persistent cookies. |
max-age=<seconds> |
Sets relative lifetime in seconds (0 or negative deletes immediately). |
path=/ |
Restricts URL path scope; / makes the cookie available across the entire site. |
domain=example.com |
Controls host and subdomain visibility of the cookie. |
Secure |
Ensures the browser transmits the cookie only over encrypted HTTPS connections. |
SameSite=Strict|Lax|None |
Mitigates Cross-Site Request Forgery (CSRF) by restricting cross-origin transmission. |
HttpOnly |
Server-set flag blocking JavaScript document.cookie access to prevent XSS theft. |
function setCookie(name, value, daysValid) {
const maxAgeSeconds = daysValid * 24 * 60 * 60;
document.cookie =
encodeURIComponent(name) + "=" + encodeURIComponent(value) +
"; max-age=" + maxAgeSeconds +
"; path=/; SameSite=Lax";
}
function getCookie(name) {
const targetKey = encodeURIComponent(name) + "=";
const pairs = document.cookie.split("; ");
for (const pair of pairs) {
if (pair.startsWith(targetKey)) {
return decodeURIComponent(pair.slice(targetKey.length));
}
}
return null;
}
function deleteCookie(name) {
document.cookie = encodeURIComponent(name) + "=; max-age=0; path=/";
}
setCookie("theme", "dark", 7);
console.log("Active theme:", getCookie("theme"));1.3 Cookies vs Web Storage (localStorage and sessionStorage)
While cookies automatically travel to the server in HTTP headers on every matching request (consuming upload bandwidth), modern HTML5 Web Storage APIs (localStorage and sessionStorage) store larger volumes of data (5–10 MB) strictly on the client without automatic server transmission. Consequently, cookies remain best suited for compact authentication tokens and server-readable preferences, whereas localStorage is preferred for larger client-side UI state.
Chapter 2: Introduction to React Router and Single-Page Navigation
2.1 Client-Side Routing vs Server-Side Routing
In traditional multi-page web applications, clicking a link sends a fresh HTTP GET request to the server, which returns a brand-new HTML document and reloads the entire page. In a React Single Page Application (SPA), client-side routing intercepts URL changes using the browser's HTML5 History API (history.pushState), updates the address bar without triggering a full-page reload, and swaps only the matching React components on screen.
React Router (installed as react-router-dom) is the standard declarative routing library for React web applications. It synchronizes UI views seamlessly with the browser URL, enabling bookmarkable deep links, browser back/forward button support, and nested layouts.
2.2 Setting Up Routes in React Applications
In React Router v6, routing is configured using three core components:
<BrowserRouter>: Wraps the root application (typically inindex.jsorApp.js) to provide routing context using clean HTML5 history URLs.<Routes>: Inspects all child<Route>definitions and renders the single best-matching route for the current URL.<Route path="..." element={...} />: Maps a URL path pattern to the React element to render. A path of"*"acts as a wildcard fallback for 404 Not Found pages, while nested routes share a parent layout component containing an<Outlet />placeholder.
import { BrowserRouter, Routes, Route, Outlet } from "react-router-dom";
function DashboardLayout() {
return (
<div>
<h2>Student Portal</h2>
<Outlet /> {/* Nested child route renders here */}
</div>
);
}
export default function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/courses" element={<CourseList />} />
<Route path="/portal" element={<DashboardLayout />}>
<Route index element={<PortalOverview />} />
<Route path="grades" element={<GradesView />} />
</Route>
<Route path="*" element={<h3>404 - Page Not Found</h3>} />
</Routes>
</BrowserRouter>
);
}2.3 Navigating Between Routes
Using standard HTML <a href="..."> tags inside a React SPA forces a full page refresh, destroying in-memory React state. React Router provides declarative and programmatic navigation primitives instead:
<Link to="/courses">: Renders an accessible anchor element that intercepts clicks and updates the URL via the History API without reloading the page.<NavLink to="/courses">: A specializedLinkaware of whether its destination matches the active URL, exposing anisActiveflag in itsclassNameorstylecallback for highlighting active navigation tabs.useNavigate()Hook: Returns anavigatefunction for imperative programmatic navigation after events such as form submission, login success, or timer expiry (e.g.,navigate("/dashboard")ornavigate(-1)to go back).<Navigate to="/login" replace />: Declaratively redirects during render when a route guard condition is unmet.
2.4 Passing and Reading Parameters in Routes
Dynamic routes embed variable segments prefixed with a colon, such as path="/courses/:courseCode". Inside the target component, React Router hooks extract route data cleanly:
useParams(): Returns an object of key-value pairs corresponding to dynamic URL segments (for example, visiting/courses/UK2DSCCAP105yields{ courseCode: "UK2DSCCAP105" }).useSearchParams(): Reads and updates URL query strings such as/courses?sem=2&sort=ascusing a familiar[searchParams, setSearchParams]tuple.useLocation(): Returns the current location object (pathname,search,hash, and optional transient navigationstatepassed vianavigate("/detail", { state: { item } })).
import { Link, NavLink, useNavigate, useParams, useSearchParams } from "react-router-dom";
function Navbar() {
return (
<nav>
<Link to="/">Home</Link>
<NavLink
to="/courses"
style={({ isActive }) => ({ fontWeight: isActive ? "bold" : "normal" })}
>
Courses
</NavLink>
</nav>
);
}
function CourseDetail() {
const { courseCode } = useParams();
const [searchParams, setSearchParams] = useSearchParams();
const navigate = useNavigate();
const activeTab = searchParams.get("tab") || "overview";
return (
<div>
<h3>Course Code: {courseCode}</h3>
<p>Active Tab: {activeTab}</p>
<button onClick={() => setSearchParams({ tab: "syllabus" })}>View Syllabus Tab</button>
<button onClick={() => navigate(-1)}>Back</button>
</div>
);
}Chapter 3: Cookie Security, Client Storage Comparison, and Protected Routing
3.1 Cookie Security Threats and Web Storage Comparison
Because cookies are automatically attached to HTTP requests, misconfigured cookies expose web applications to two primary security vulnerabilities:
- Cross-Site Scripting (XSS): If an attacker injects malicious JavaScript into a page, that script can read
document.cookieand exfiltrate session tokens. Setting theHttpOnlyflag on the server prevents JavaScript from accessing sensitive authentication cookies altogether. - Cross-Site Request Forgery (CSRF): A malicious third-party website triggers an authenticated request to a target domain where the user is already signed in. Setting
SameSite=StrictorSameSite=Laxprevents browsers from sending cookies on cross-site subrequests.
| Feature | HTTP Cookies | localStorage | sessionStorage |
|---|---|---|---|
| Capacity Limit | ~4 KB per cookie | ~5–10 MB per origin | ~5 MB per origin |
| Sent with HTTP Requests | Yes (automatically in headers) | No (client-only) | No (client-only) |
| Lifetime | Configurable (expires / max-age) |
Persists until explicitly cleared | Cleared when browser tab closes |
| JS Accessibility | Accessible unless HttpOnly |
Accessible via JS API | Accessible via JS API |
3.2 Protected Routes, Redirects, and Location State in React Router
In real-world Single Page Applications, certain routes—such as student grade portals or admin dashboards—must be restricted to authenticated users. A Protected Route wrapper component inspects authentication state; if the user is signed in, it renders the requested child component (or <Outlet />); otherwise, it returns <Navigate to="/login" state={{ from: location }} replace />. Passing replace replaces the current history entry so clicking the browser Back button does not trap the user in a redirect loop, and storing location in state allows redirecting back to the originally requested page immediately after login.
import { Navigate, Outlet, useLocation, useNavigate, Link } from "react-router-dom";
function ProtectedRoute({ isAuthenticated }) {
const location = useLocation();
if (!isAuthenticated) {
return <Navigate to="/login" state={{ from: location.pathname }} replace />;
}
return <Outlet />;
}
function LoginPage({ onLoginSuccess }) {
const navigate = useNavigate();
const location = useLocation();
const destination = location.state?.from || "/portal";
function handleSignIn() {
onLoginSuccess();
navigate(destination, { replace: true });
}
return (
<div>
<h2>Student Sign In</h2>
<button onClick={handleSignIn}>Sign In</button>
<p><Link to="/">Return Home</Link></p>
</div>
);
}3.3 Complete Cookie-Backed Preference Manager in React
Combining JavaScript cookie helpers with React state allows user preferences (such as theme or language selection) to persist cleanly across browser reloads and remain readable by both client scripts and backend servers.
import { useState } from "react";
function readCookie(key) {
const prefix = encodeURIComponent(key) + "=";
const match = document.cookie.split("; ").find((row) => row.startsWith(prefix));
return match ? decodeURIComponent(match.slice(prefix.length)) : null;
}
function writeCookie(key, value, days) {
const seconds = days * 86400;
document.cookie =
encodeURIComponent(key) + "=" + encodeURIComponent(value) +
"; max-age=" + seconds + "; path=/; SameSite=Lax";
}
export default function ThemeSwitcher() {
const [theme, setTheme] = useState(() => readCookie("ui_theme") || "light");
function toggleTheme() {
const next = theme === "light" ? "dark" : "light";
setTheme(next);
writeCookie("ui_theme", next, 30);
}
return (
<div>
<p>Current Saved Theme: {theme}</p>
<button onClick={toggleTheme}>Switch Theme</button>
</div>
);
}Chapter 4: Complete Multi-Page SPA Architecture with React Router and Cookies
4.1 Designing Scalable Client-Side Route Hierarchies
As a React Single Page Application grows, organizing routes into modular layout shells prevents duplicated navigation bars and footers. In React Router v6, a parent <Route element={<AppLayout />}> renders a persistent header, sidebar, and footer around an <Outlet /> component, while child routes swap content inside the outlet seamlessly. Using an index route renders the default landing view when the parent path matches exactly.
When deploying a React Router application using BrowserRouter to static hosting (such as Nginx, Apache, Netlify, or Vercel), the web server must be configured to serve index.html for all unknown URL paths (fallback rewrite). Without this server rewrite rule, refreshing the browser directly on a deep link like /courses/UK2DSCCAP105 causes the web server to look for a physical file at that path and return a 404 error before React Router can boot.
| React Router API | Category | Primary Responsibility |
|---|---|---|
<BrowserRouter> |
Router Provider | Syncs React UI with browser URL using HTML5 history.pushState. |
<Routes> & <Route> |
Route Matching | Declares URL path patterns and renders the single best-matching element. |
<Outlet /> |
Layout Placeholder | Marks where matched child routes render inside a parent layout component. |
<Link> & <NavLink> |
Declarative Navigation | Navigates without full page reload; NavLink exposes active route styling. |
useParams() |
Hook | Extracts dynamic URL path parameters such as :courseCode or :id. |
useSearchParams() |
Hook | Reads and updates URL query parameters (e.g., ?semester=2&filter=core). |
useNavigate() |
Hook | Performs imperative navigation after events or history back/forward steps. |
useLocation() |
Hook | Inspects current pathname, search, and transient navigation state. |
4.2 Worked End-to-End Application: Course Catalog with Cookies & Routing
The following integrated example combines JavaScript cookie persistence (remembering the student's preferred semester filter) with React Router navigation, dynamic route parameters, query search parameters, and active link highlighting.
import { useState } from "react";
import {
BrowserRouter,
Routes,
Route,
NavLink,
Link,
Outlet,
useParams,
useSearchParams,
useNavigate
} from "react-router-dom";
const COURSES = [
{ code: "UK2DSCCAP105", title: "Modern Web Technologies", sem: "2", credits: 4 },
{ code: "UK2DSCCAP104", title: "Data Structures", sem: "2", credits: 4 },
{ code: "UK1DSCCAP101", title: "Problem Solving in C", sem: "1", credits: 4 }
];
function getCookieValue(name) {
const key = encodeURIComponent(name) + "=";
const part = document.cookie.split("; ").find((c) => c.startsWith(key));
return part ? decodeURIComponent(part.slice(key.length)) : null;
}
function setCookieValue(name, val, days) {
document.cookie =
encodeURIComponent(name) + "=" + encodeURIComponent(val) +
"; max-age=" + (days * 86400) + "; path=/; SameSite=Lax";
}
function MainLayout() {
return (
<div>
<header>
<NavLink to="/" style={({ isActive }) => ({ fontWeight: isActive ? "bold" : "normal" })}>
Home
</NavLink>{" | "}
<NavLink to="/courses" style={({ isActive }) => ({ fontWeight: isActive ? "bold" : "normal" })}>
Courses
</NavLink>
</header>
<main>
<Outlet />
</main>
</div>
);
}
function CourseListPage() {
const [searchParams, setSearchParams] = useSearchParams();
const [savedSem, setSavedSem] = useState(() => getCookieValue("preferred_sem") || "all");
const activeSem = searchParams.get("sem") || savedSem;
function handleFilterChange(sem) {
setSavedSem(sem);
setCookieValue("preferred_sem", sem, 14);
setSearchParams(sem === "all" ? {} : { sem });
}
const filtered = activeSem === "all"
? COURSES
: COURSES.filter((c) => c.sem === activeSem);
return (
<section>
<h2>BCA Course Catalog (Filter: {activeSem})</h2>
<button onClick={() => handleFilterChange("all")}>All</button>
<button onClick={() => handleFilterChange("1")}>Semester 1</button>
<button onClick={() => handleFilterChange("2")}>Semester 2</button>
<ul>
{filtered.map((course) => (
<li key={course.code}>
<Link to={"/courses/" + course.code}>{course.code} - {course.title}</Link>
</li>
))}
</ul>
</section>
);
}
function CourseDetailPage() {
const { code } = useParams();
const navigate = useNavigate();
const course = COURSES.find((c) => c.code === code);
if (!course) {
return (
<div>
<p>Course not found.</p>
<button onClick={() => navigate("/courses")}>Back to Catalog</button>
</div>
);
}
return (
<article>
<h2>{course.title}</h2>
<p>Course Code: {course.code} | Semester: {course.sem} | Credits: {course.credits}</p>
<button onClick={() => navigate(-1)}>Go Back</button>
</article>
);
}
export default function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<MainLayout />}>
<Route index element={<h1>Welcome to BCA Academic Portal</h1>} />
<Route path="courses" element={<CourseListPage />} />
<Route path="courses/:code" element={<CourseDetailPage />} />
<Route path="*" element={<h2>404 - Route Not Found</h2>} />
</Route>
</Routes>
</BrowserRouter>
);
}Chapter 5: Code Splitting, Lazy Routes, and Practical Deployment Checklist
5.1 Route-Based Code Splitting with React.lazy and Suspense
In large Single Page Applications, bundling every route's JavaScript into a single file increases initial page load time. React Router pairs seamlessly with React.lazy() and <Suspense> to perform route-based code splitting: each route's component bundle is downloaded on demand only when the user navigates to that route, keeping the initial bundle lean and responsive.
import { lazy, Suspense } from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
const HomePage = lazy(() => import("./pages/HomePage"));
const AnalyticsPortal = lazy(() => import("./pages/AnalyticsPortal"));
export default function LazyAppRouter() {
return (
<BrowserRouter>
<Suspense fallback={<p>Loading module view...</p>}>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/analytics" element={<AnalyticsPortal />} />
</Routes>
</Suspense>
</BrowserRouter>
);
}5.2 Cookie & Router Production Verification Checklist
Before deploying a React SPA that integrates JavaScript cookies and client-side routing, engineers should verify four critical invariants: (1) all authentication cookies are issued by the backend with HttpOnly, Secure, and SameSite=Lax flags; (2) client-side preference cookies use explicit path=/ and encodeURIComponent() sanitization; (3) the production web server rewrites unknown paths to index.html so deep links work on hard refresh; and (4) a wildcard path="*" fallback route handles genuinely invalid URLs gracefully with a clear navigation link back to home.
5.3 Comparing HashRouter vs BrowserRouter
While <BrowserRouter> produces clean, standard URLs (such as https://example.com/courses/105) using the HTML5 History API, legacy static servers that cannot be configured with an index.html fallback rewrite can use <HashRouter>. HashRouter stores the route path after the URL hash symbol (https://example.com/#/courses/105). Because browsers never transmit the hash fragment to the server in HTTP requests, deep links resolve without server configuration, at the cost of less clean URLs and limited server-side rendering compatibility. For modern production deployments, BrowserRouter remains the recommended standard.
University of Kerala FYUGP Academic Framework
Syllabus details for BCA Semester 2 under official University of Kerala regulations.
Assessment comprises a 70-mark End-Semester Examination (2.5 Hours) and 30-mark Continuous Internal Evaluation.
About Modern Web Technologies (University of Kerala BCA Sem 2)
Modern Web Technologies (UK2DSCCAP105 • 4 Credits • 60 Hours (4 Hrs/Week)) is a DSC offering under the Bachelor of Computer Applications (BCA) Four-Year Undergraduate Programme (UoK FYUGP Regulations 2024 / 2025) at the University of Kerala. Structured across five sequentially integrated instructional modules, the course builds solid theoretical foundations and hands-on technical proficiency in modern web technologies. Students engage with core computing principles, structured problem-solving, implementation techniques, and modern industry practices aligned with Kerala State Higher Education Council outcome-based education standards.
Modern Web Technologies Module-by-Module Curriculum Breakdown
Official syllabus unit modules prescribed by the University of Kerala FYUGP framework:
JavaScript: Introduction
Modern web applications rely on a three-layer client-side architecture: HyperText Markup Language (HTML) defines document structure and semantics, Cascading Style Sheets (CSS) governs visual presentation and responsive layout, and JavaScript supplies programmable behavior, interactivity, and asynchronous communication. Originally created in 1995 by Brendan Eich at Netscape as a lightweight scripting language for browser interactivity, JavaScript has evolved into a standardized general-purpose programming language governed by the ECMAScript specification (ECMA-262).
JavaScript: Arrays, Objects, Events, Form and Exception Handling
An array in JavaScript is an ordered, zero-indexed, dynamically resizable collection capable of storing heterogeneous values—numbers, strings, booleans, objects, or even nested arrays. Arrays are specialized objects whose length property updates automatically as elements are added or removed. While new Array() exists, the array literal syntax [...] is the standard idiom because it avoids ambiguity when passing a single numeric argument.
React JS: Introduction
As web applications grew from static multi-page documents into rich Single Page Applications (SPAs), direct imperative manipulation of the browser Document Object Model (DOM) using vanilla JavaScript or jQuery became error-prone and slow. In traditional imperative programming, developers manually locate DOM nodes, mutate attributes, attach listeners, and synchronize UI state across dozens of views. Frequent unbatched DOM writes trigger expensive browser layout recalculations (reflows) and repaints.
React JS: Events, Styles, Forms in React JS
While props carry read-only configuration from parent to child, state represents private, mutable data owned and managed internally by a component that changes over time—such as form input text, toggle flags, fetched API records, or active tab indices. Whenever a component's state changes, React automatically schedules a re-render of that component and its subtree to keep the UI synchronized. In class-based React components (which extend React.
Flexi Module: Cookies in JavaScript & React Router
The Hypertext Transfer Protocol (HTTP) is inherently stateless: each request from a browser to a server is independent and carries no built-in memory of prior requests. To maintain user sessions, shopping carts, language preferences, and personalization across page loads, browsers support HTTP cookies —small key-value text records (typically capped at approximately 4 KB per cookie) stored by the browser and automatically attached to subsequent HTTP requests to the matching origin.
Core Curriculum & Key Topics
- Introduction to JavaScript and Language Fundamentals
- 1 Evolution and Role of JavaScript in Modern Web Architecture
- 2 Embedding JavaScript in HTML Documents
- 3 Variables, Scope, Hoisting, and Declaration Keywords
- 4 Data Types and Dynamic Typing
- Operators, Expressions, and Control Structures
- 1 Expressions, Operators, and Precedence
- 2 Conditional Control Structures
Learning Outcomes
- Demonstrate authoritative comprehension of the foundational concepts, architectures, and principles of modern web technologies.
- Apply algorithmic, programming, or analytical techniques to design and evaluate practical computing solutions.
- Analyze system trade-offs, security considerations, and industry standards relevant to modern software and IT environments.
- Implement, test, and document structured technical workflows aligned with professional computing practices.
- Achieve exam-ready mastery of University of Kerala FYUGP BCA question patterns across short concepts, technical comparisons, and comprehensive essays.
University of Kerala Examination Scheme for Modern Web Technologies
The evaluation framework for Modern Web Technologies (UK2DSCCAP105) under University of Kerala FYUGP regulations combines Continuous Internal Evaluation (30 Marks) with the university End-Semester Examination (70 Marks) for a total of 100 Marks (2.5 Hours duration):
10 Questions × 3 Marks (Maximum ceiling 24 Marks). Short definitional and conceptual questions covering all 5 syllabus modules.
8 Questions × 6 Marks (Maximum ceiling 36 Marks). Paragraph questions, comparative evaluations, and analytical problems.
2 Questions × 10 Marks (Answer any 1 for 10 Marks). Long-form essay or comprehensive numerical workout problem.
Exam Preparation Strategy:
To score top marks in the University of Kerala UK2DSCCAP105 (Modern Web Technologies) examination: 1. Write Clean, Traceable Code Snippets: Always include well-indented syntax examples with sample input and expected output for programming questions. 2. Explain Logic & Control Flow Step-by-Step: Before writing full programs, briefly outline the algorithm, key functions, or class hierarchy so examiners can award full step marks. 3. Highlight Edge Cases & Syntax Rules: Mention common runtime pitfalls, data type constraints, or security/validation practices where relevant. 4. Manage Time Across Sections: For the 2.5-hour 70-mark external paper, allocate 25 minutes to Part A definitions, 50 minutes to Part B short programs and comparisons, and 75 minutes to Part C full code-backed essays.
Exam Preparation & Study Guides — Modern Web Technologies
What is Introduction to JavaScript and why is it important in Modern Web Technologies?
JavaScript (standardized as ECMAScript / ECMA-262) is a high-level, dynamically typed, prototype-based, multi-paradigm scripting language executed by Just-In-Time (JIT) engines such as Google V8 and SpiderMonkey to add interactivity, DOM manipulation, and asynchronous behavior to web pages.
What is Control Structures (Conditionals and Loops) and why is it important in Modern Web Technologies?
Control flow statements govern conditional branching and repeated iteration.
What is Working with Arrays and why is it important in Modern Web Technologies?
Arrays are zero-indexed, dynamically sized ordered lists supporting mutating, accessor, and higher-order functional methods.
What are the core elements of ES6 Collections, Prototypes, and Safe Access in Modern Web Technologies?
Modern JavaScript complements arrays and plain objects with specialized collections and defensive operators.
What is Creating, Rendering Components, and Props and why is it important in Modern Web Technologies?
React applications compose PascalCase components mounted into the DOM via
What is the official course code and credit structure for Modern Web Technologies at University of Kerala?
Modern Web Technologies carries the official course code UK2DSCCAP105 under the University of Kerala FYUGP BCA framework. It is awarded 4 credits (60 Hours (4 Hrs/Week)), evaluated through 30 marks Continuous Internal Evaluation (CIE) and 70 marks End-Semester Examination (ESE).
Where can students download free PDF notes for Modern Web Technologies?
Students can read all 5 module notes online and download verified chapter-wise PDFs, combined exam notes, and quick revision sheets for Modern Web Technologies (UK2DSCCAP105) directly from DegreeLive (degreelive.in) with zero paywalls or sign-ups.
Course outlines and study notes follow official University of Kerala curricula. Curated by Anoop (Thiruvananthapuram).
For feedback or corrections, contact [email protected].
Related Study Resources & Student Support
Related Semester 2 Subjects
Browse study notes for other courses in BCA Sem 2:
Financial Aid & Grants 2026-27
Check eligibility criteria and deadlines for Kerala government and merit scholarships (e-Grantz 3.0, KSHEC, DCE).
Request Notes
Can't find what you're looking for? Let us know which subject notes you need.