0% found this document useful (0 votes)
44 views29 pages

Web Development Exam Questions: HTTP, XML, DOM

Uploaded by

2024ca73d
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views29 pages

Web Development Exam Questions: HTTP, XML, DOM

Uploaded by

2024ca73d
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Web Development: HTTP, JavaScript, and

React Exam Questions

Unit 1
1) What is HTTP? Explain its working along with request and response
example (5M)
HTTP, which stands for HyperText Transfer Protocol, is a protocol used to
access data on the World Wide Web (WWW). It can transfer data in various
forms, including plain text, hypertext, audio, and video. HTTP is known as
HyperText Transfer Protocol due to its efficiency in hypertext environments,
allowing for rapid jumps between documents. It is simpler than FTP, using only
one connection for transfers, and delivers messages immediately, unlike SMTP
which stores and forwards them.
Working of HTTP: HTTP operates as a request-response protocol, enabling
users to interact with web resources like HTML files by transmitting hypertext
messages between clients and servers. HTTP clients typically use
Transmission Control Protocol (TCP) connections for communication.
The HTTP transaction involves a client initiating a request message to the
server, and the server responding with a response message. HTTP messages
are of two types: request and response, both following the same format.

Request Message: This message is sent by the client and typically consists
of a request line, headers, and sometimes a body.

Response Message: This message is sent by the server to the client and
includes a status line, headers, and sometimes a body.

Example of Request and Response: An example of an HTTP request message


is: GET / HTTP/1.1 Host: [Link] Accept-Language: fr
An example of an HTTP response message includes: Status code: HTTP/1.1 200 OK

Date: Sat, 29 Oct 2009 [Link] GMT Server: Apache Last-Modified: Tue, 01 Dec 2009 [Link] GMT Etag:

"5114298-29769-d7b2891b" Accept-Ranges: bytes Content-Length: 29769 Content-Type: text/html

2) Write an XML file [Link] representing your semester mark sheet.


How do you prove that it is well formed and valid XML? (5M)

Untitled 1
XML, which stands for Extensible Markup Language, is a text-based markup
language used for storing and transporting data.
How to prove an XML file is well-formed: To prove that an XML file, such as
[Link] , is well-formed, it must adhere to the following rules:

It must begin with the XML declaration (e.g., <?xml version="1.0"?> ).

It must have one unique root element.

All start tags must match their corresponding end tags.

XML tags are case sensitive.

All elements must be closed.

All elements must be properly nested.

All attributes' values must be quoted.

XML entities must be used for special characters.

How to prove an XML file is valid: To prove that an XML file, such as
[Link] , is valid, it must be validated against a Document Type Definition

(DTD) or XML Schema.

A DTD defines the legal building blocks of an XML document and its
attributes.

An XML Schema Definition (XSD) defines the structure of an XML


document in more detail than a DTD and provides better control over XML
structure.

3) Draw and illustrate 3-tier web architecture. (5M)

Three Tier Web Architecture


Three-tier architecture is an architecture pattern used in applications as a
specific type of client–server system.

The Three-Tier Web Architecture is a unique system of developing web


database applications, which consists of:

Data Tier (bottom) – database and data storage.

Application Tier (middle) – business logic and processing.

Presentation Tier (top) – user interface at the client end.

Untitled 2
This architecture provides a framework for most web applications on the
internet. It separates the business logic from the application logic and
database.

Functions of Each Layer


1. Presentation Tier
The top level of the application.

Sends content to be viewed on the client side.

Uses frameworks such as HTML, CSS, JavaScript.

Displays information in a graphical interface (GUI).

Communicates with other layers via API calls.

2. Application Tier
Also called the business logic layer.

Bridges the gap between the presentation layer and data layer.

Handles business logic, data processing, and communication.

Usually coded in C#, Java, C++, Python, Ruby, etc.

3. Data Tier
Consists of persistent storage mechanisms (databases).

Stores, retrieves, and updates data.

Supports communication with the database using queries (e.g., SQL).

Advantages
1. Improved Data Integrity.

2. High degree of flexibility in deployment and configuration.

3. Improved security.

4. High performance and persistent objects.

5. Future scalability (more users and resources can be supported).

Untitled 3
6. Easier code maintenance and modification.

7. Code and data reusability.

Disadvantages
1. More complex compared to 1-tier and 2-tier.

2. Higher cost of network maintenance and deployment.

4) Write a short note on Document Object Model (DOM). (5M)

DOM (Document Object Model)


The Document Object Model (DOM) is a programming interface for HTML and
XML (Extensible Markup Language).
It defines the logical structure of documents and the way a document is
accessed and manipulated.

DOM represents the document as a tree structure.

Each node in the tree is an object and corresponds to a part of the


document.

The W3C DOM standard is separated into three different parts/levels:

1. Core DOM – standard model for any structured document.

2. XML DOM – standard model for XML documents.

3. HTML DOM – standard model for HTML documents.

1.9.1 XML DOM


XML DOM is a standard object model for XML.

XML documents have a hierarchy of information called nodes; DOM is a


standard programming interface for processing XML documents.

An XML DOM also provides an API that allows a programmer to add, edit,
move or remove nodes at any point in the tree, and to retrieve information.

1.9.2 HTML DOM

Untitled 4
The HTML DOM is a standard object model and programming interface for
HTML.

It defines:

1. The HTML elements as objects.

2. The properties of all HTML elements.

3. The methods to access all HTML elements.

4. The events for all HTML elements.

Properties of Document Object


The properties of the document object that are most widely used in developing
user-friendly applications:

1. Window Object: A Window Object is always at the top of the hierarchy.

2. Document Object: When an HTML document is loaded into a window, it


becomes a Document Object.

3. Form Object: It is represented by form tags.

4. Form Control Elements: Form elements vary and can be checkboxes, text
areas, radio buttons, buttons, etc.

Methods of Document Object


write(string): writes the given string on the document.

getElementById(): returns element having the given id.

getElementsByName(): returns all the elements having the given name


value.

getElementsByTagName(): returns all the elements having the given tag


name.

getElementsByClassName(): returns all the elements having the given


class name.

✅ Advantages of XML DOM

Untitled 5
Data-Centric → Stores and transports structured data.
Platform Independent → Works across different systems.
Self-Descriptive → Tags describe the data clearly.
Hierarchical Structure → Makes data easy to parse and manipulate.
Separation of Data & Presentation → Focuses only on data, not design.

✅ Advantages of HTML DOM


Document Representation → Represents web pages as a tree structure.
Dynamic Content → Allows adding, deleting, or changing elements on
webpages.
Event Handling → Supports events like click, hover, input, etc.
Cross-Platform → Works in all browsers consistently.
Integration with JavaScript → Enables interactive and responsive webpages

1.9.3 Levels of DOM: Low-level set of Interfaces


Level 1 DOM: can be described in two parts; CORE and HTML.

CORE provides low-level interfaces that can be used to represent any


structured document.

HTML provides high-level interfaces for HTML documents.

Level 2 DOM: provides new functionalities such as mouse and user interface
events, CSS, Range, and Traversal.
Level 3 DOM: consists of all level 1 and 2 functionalities plus new specifications
like XPath, Load and Save, and Validation.

Example of DOM Manipulation:


<html>
<head>
<title>DOM manipulation</title>
</head>
<body>
Enter Value 1: <input type="text" id="val1">
<br>
Enter Value 2: <input type="text" id="val2">
<br>

Untitled 6
<button onclick="getAdd()">Click To Add</button>
<p id="result"></p>

<script type="text/javascript">
function getAdd() {
var num1 = Number([Link]('val1').value);
var num2 = Number([Link]('val2').value);
var sum = num1 + num2;

[Link]('result').innerHTML = "Addition = " + sum;


[Link]('result').[Link] = 'red';
}
</script>
</body>
</html>

5) Explain the working of DNS with the suitable diagrams. Clearly explain all
the steps involved in DNS resolution.
DNS (Domain Name System) is an application layer protocol that defines how
applications on different systems pass messages. It acts as a directory service
that maps hostnames on a network to their corresponding numerical IP
addresses. DNS translates human-friendly domain names into IP addresses,
making it easier for users to access hosts without remembering complex IP
addresses.
Working of DNS: DNS operates as a client/server network communication
protocol, where DNS clients send requests and DNS servers send responses.

Forward DNS lookups involve converting a name into an IP address.

Reverse DNS lookups involve converting an IP address into a name. DNS


implements a distributed database to store the names of all hosts on the
internet.

Steps involved in DNS resolution (Working of DNS with diagram):

1. When a user enters a web address or URL (e.g., [Link] ) into their
browser, the request is passed to a Domain Name Server (DNS).

Untitled 7
2. The DNS server holds a list of system names and their corresponding IP
addresses, converting the typed address into a numerical IP that identifies the
destination computer.
3. The browser, acting as a client, sends the request to the server using HTTP,
based on the IP address provided by the DNS server.

4. If the local DNS server does not have the IP address associated with the
hostname, it forwards the request to another DNS server. This process
involves querying root nameservers, then TLD (Top-Level Domain)
nameservers, and finally authoritative nameservers until the IP address is
found.
5. Once the IP address is obtained, it is sent back to the resolver, which then
completes the request over the internet protocol.
6. The server that hosts the website receives the request, gathers the
information about the requested document, and sends it back to the browser's
IP address.

7. The browser then gathers all the requested information and displays it on the
user's device screen in the form of web pages. This may involve the browser
requesting additional linked files, such as images, from the same server.

Unit 2
1) Write a Javascript to change the background color of the web page to red
color if button named “RED” is clicked and to green color if button named
“GREEN” is clicked. (5M)

<html>
<head>
<title>Hello Webpage</title>
<script type="text/javascript">
function changebg_red() {
[Link] = 'red';
}
function changebg_green() {
[Link] = 'green';
}
</script>
</head>
<body>

Untitled 8
<form>
<input type="button" value="RED" onclick="changebg_red()">
<input type="button" value="GREEN" onclick="changebg_green()">
</form>
</body>
</html>

2) Write JavaScript to validate Username, Password and Email. Username


and Password should not be blank and minimum length of password =8.
Email should have @ character. (10M)

<html>
<head>
<title>JavaScript form validation programs</title>
<script type="text/javascript">
function validateForm() {
var uname = [Link]["myform"]["username"].value;
var pword = [Link]["myform"]["password"].value;
var email = [Link]["myform"]["email"].value;

// Username Validation: Should not be blank


if (uname == "") {
alert("Please enter username");
return false;
}

// Password Validation: Should not be blank and minimum length of


8
if (pword == "") {
alert("Please enter password");
return false;
} else if ([Link] < 8) {
alert("Password should be a minimum of 8 characters!");
return false;
}

// Email Validation: Should have @ character


if (email == "") {

Untitled 9
alert("Please enter email address");
return false;
} else if ([Link]("@") == -1) {
alert("Email should have @ character!");
return false;
}

return true; // If all validations pass


}
</script>
</head>
<body>
<form name="myform" onsubmit="return validateForm()">
Username: <input type="text" name="username"><br><br>
Password: <input type="password" name="password"><br><br>
Email: <input type="text" name="email"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

3) Write a Javascript to accept two numbers and display their sum using pop
up box. (5M)

<html>
<head>
<script type="text/javascript">
var num1 = parseInt(prompt("Enter First number "));
var num2 = parseInt(prompt("Enter Second number "));
var sum = num1 + num2;
alert("Sum = " + sum);
</script>
</head>
<body>
<h1>JavaScript Pop Up Box Example</h1>
<p>This page uses JavaScript to ask for two numbers and display their s
um in an alert box.</p>

Untitled 10
</body>
</html>

4) Differentiate ES5 and ES6. Give an example of the Anonymous and Arrow
function in ES6. (5M)
Differentiation between ES5 and ES6:

Parameter ES5 ES6 Source(s)

The fifth edition of the The sixth edition of the


ECMAScript, a ECMAScript, a
Definition trademarked scripting trademarked scripting
language specification language specification
by ECMA International. by ECMA International.

Release Introduced in 2009. Introduced in 2015.

Adds some new


Supports primitive data JavaScript data types. It
types that are string, introduced a new
Data-types
number, boolean, null, primitive data type
and undefined. 'symbol' for supporting
unique values.

New ways to define


Defining Variables are defined
variables using let and
Variables using the var keyword.
const .

Higher performance than


Lower performance ES5 due to new features
Performance
than ES6. and shorthand storage
implementation.

A wide range of Has a lot of community


Support communities supports support, but it is lesser
it. than ES5.

Due to destructuring and


spread operators, object
Object Time-consuming than
manipulation can be
Manipulation ES6.
processed more
smoothly.

Both function and A new feature by which


Arrow return keywords are the function keyword is
Functions used to define a not required to define the
function. function.

Untitled 11
Introduced the concept
of for...of loop to
The for loop is used to
Loops perform iteration over
iterate over elements.
the values of iterable
objects.

Example of Anonymous Function in ES6: An anonymous function is a function


without a name. It is dynamically declared and not bound with an identifier.

var hello = function() {


[Link]("Hello World");
[Link]("I am an anonymous function");
}
hello(); // Output: Hello World, I am an anonymous function

Example of Arrow Function in ES6: Arrow functions are a new feature in ES6
that allow for a shorter syntax compared to regular function expressions. They
are anonymous and do not require the function keyword.

var myfun3 = () => {


[Link]("It is an Arrow Function");
}
myfun3(); // Output: It is an Arrow Function

A simpler example:

var show = () => [Link]("Hello World");


show(); // Output: Hello World

5) Write a Javascript to accept a number from the user and check if it is even
or odd (5M)

<html>
<head>
<script type="text/javascript">
var num = prompt("Enter a number ");
if (num % 2 == 0) {
alert("Number is Even = " + num);
} else {

Untitled 12
alert("Number is Odd = " + num);
}
</script>
</head>
<body>
<h1>JavaScript Even or Odd Check</h1>
<p>This page uses JavaScript to check if a number entered by the user i
s even or odd.</p>
</body>
</html>

6) Write a Javascript Program that changes the background color of page by


refreshing the page every 2 seconds (5M)

<html>
<head>
<script type="text/javascript">
function changebgcolor() {
var a = [Link];
[Link] = [Link] == "red" ? "yell
ow" : "red";
// The original source changes color every 5000 milliseconds (5 sec
onds).
// To change it every 2 seconds as per the query, this value should
be 2000.
setTimeout(changebgcolor, 2000); // Changes background color ev
ery 2 seconds
}
</script>
</head>
<body onload="changebgcolor()">
<h1>Background Color Changer</h1>
<p>This page's background color will change automatically every 2 seco
nds.</p>
</body>
</html>

Untitled 13
7) Differentiate between ES5 and ES6. Describe the concepts of Arrow
Functions, classes and inheritance in JavaScript. (10M)

Concepts in JavaScript:

Arrow Functions: Arrow functions are a new feature introduced in ES6 that
provide a concise syntax for writing function expressions, eliminating the need
for the function keyword. They are anonymous functions (functions without a
name and not bound with an identifier).

Syntax: Arrow functions typically follow the syntax (parameters) => { function body

} .

Untitled 14
Context (this): One significant advantage is that the this context within
arrow functions is lexically or statically defined, meaning it inherits this
from the enclosing scope, unlike regular functions where this depends on
how the function is called.

Conciseness: They reduce code size and simplify function definitions.

Implicit Return: For single-expression bodies, the return keyword can be


omitted for an implicit return.

Use Cases: Often used for callbacks and methods where the this context
needs to be preserved.

Classes: In JavaScript ES6, classes are a syntactic sugar over JavaScript's


existing prototype-based inheritance model, providing a more familiar object-
oriented programming (OOP) syntax. They serve as blueprints for creating
objects and help organize code into reusable, logical parts.

Definition: A class definition can include a constructor and functions


(methods). The constructor is responsible for allocating memory for class
objects.

Instantiation: Objects are instantiated from classes using the new keyword.

Data Members and Actions: Classes contain data members (properties)


and functions (methods) that perform actions related to the objects.

Encapsulation: They allow for encapsulating data and behaviour together.

Inheritance: Inheritance is an OOP concept where a new entity (subclass/child


class) is created by inheriting properties and behaviours from an existing entity
(superclass/parent class). This mechanism promotes code reusability and
allows for extending existing functionalities without rewriting them.

Types of Inheritance (as categorized in sources):

◦ Single-level Inheritance: A derived class inherits from only one base class.
◦ Multiple Inheritance: (Note: The source states "Multiple Inheritance, a class
can be inherited from several classes. It is not supported in ES6.")
◦ Multi-level Inheritance: A derived class is created from another derived
class, forming a chain of inheritance.

Key Aspects of Inheritance:

Untitled 15
◦ Code Reusability: It allows derived classes to inherit behaviour and
properties, reducing repetitive code.
◦ Extensibility: Child classes can add new features while retaining those from
the parent.
◦ extends keyword: In ES6, the extends keyword is used to establish an
inheritance relationship between classes.

8) Write a JavaScript code for displaying a digital clock on a web page (5M)

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Digital Clock</title>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<style>
:root{
--bg: #000000; /* full black background */
--card-bg: #ffffff; /* white card */
--text-dark: #111111; /* dark text for card */
--muted: #666666;
--accent: #ff7a18; /* warm accent for button */
--shadow: rgba(0,0,0,0.35);
}

/* Full-page black background and center layout */


html,body{
height:100%;
margin:0;
font-family: system-ui, -apple-system, 'Segoe UI', Roboto, Arial, sans-s
erif;
background: var(--bg);
display:flex;
align-items:center;
justify-content:center;
-webkit-font-smoothing:antialiased;
-moz-osx-font-smoothing:grayscale;
}

Untitled 16
/* White card */
.clock {
background: var(--card-bg);
color: var(--text-dark);
padding:28px 36px;
border-radius:10px;
box-shadow: 0 12px 40px var(--shadow);
text-align:center;
width:360px;
max-width:92%;
border: 1px solid rgba(0,0,0,0.06);
}

.time {
font-size:54px;
font-weight:700;
letter-spacing:1px;
margin:0;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, "Roboto
Mono", monospace;
}

.date {
margin-top:10px;
color: var(--muted);
font-size:15px;
}

.controls {
margin-top:14px;
display:flex;
justify-content:center;
gap:10px;
}

/* Styled button that looks modern and clickable */


.btn {

Untitled 17
appearance:none;
-webkit-appearance:none;
border: none;
background: var(--accent);
color: #fff;
padding:10px 14px;
border-radius:8px;
font-weight:600;
cursor:pointer;
box-shadow: 0 6px 18px rgba(255,122,24,0.18);
transition: transform 120ms ease, box-shadow 120ms ease, opacity 120
ms ease;
}
.btn:hover { transform: translateY(-2px); }
.btn:active { transform: translateY(0); opacity:0.95; }
.btn:focus { outline: 3px solid rgba(255,122,24,0.18); outline-offset:3px; }

/* Secondary control (if needed) */


.btn-ghost {
background: transparent;
color: var(--text-dark);
border: 1px solid rgba(0,0,0,0.08);
box-shadow: none;
}

@media (max-width:420px){
.time { font-size:44px; }
.clock { padding:18px; width:320px; }
}
</style>
</head>
<body>
<div class="clock" id="clock" role="region" aria-label="Digital clock">
<div class="time" id="time">--:--:--</div>
<div class="date" id="date">Loading...</div>

<div class="controls">
<button class="btn" id="toggleFormat">Use 24-hour</button>

Untitled 18
<!-- Example of another control if you want later:
<button class="btn btn-ghost" id="toggleTheme">Theme</button>
-->
</div>
</div>

<script>
const timeEl = [Link]('time');
const dateEl = [Link]('date');
const toggleBtn = [Link]('toggleFormat');

// state
let use24Hour = true;
let timerId = null;

function pad(n){ return n < 10 ? '0' + n : String(n); }

function updateClock(){
const now = new Date();
let h = [Link]();
const m = [Link]();
const s = [Link]();

let label = '';


if (!use24Hour){
label = (h >= 12) ? ' PM' : ' AM';
h = h % 12;
if (h === 0) h = 12;
}

// show HH:MM:SS and optional AM/PM


[Link] = `${pad(h)}:${pad(m)}:${pad(s)}${label}`;

// nicer date string: Weekday, Month Day, Year


const opts = { weekday: 'long', year: 'numeric', month: 'long', day: 'num
eric' };
[Link] = [Link](undefined, opts);
}

Untitled 19
// toggle button updates label and format
[Link]('click', () => {
use24Hour = !use24Hour;
[Link] = use24Hour ? 'Use 24-hour' : 'Use 12-hour';
updateClock(); // immediate reflect change
});

// Start clock
function startClock(){
if (timerId) clearInterval(timerId);
updateClock();
timerId = setInterval(updateClock, 1000);
}

startClock();
</script>
</body>
</html>

9) Explain the Document Object Model using a diagram. Write a code in


JavaScript for any one of the following: 1) To change the background color of
the web page automatically after every 5 seconds. 2) To display three radio
buttons on the web page, namely, “Red”, “Blue” and “Green”. Selecting any
button changes the background color as per the name of the button. (10M)
Explain the Document Object Model using a diagram: (This explanation is
provided in detail under Question 4 of Unit 1. Please refer to that section for the
comprehensive description of DOM and its concepts.)
(Please refer to Fig. 1.9.1 in Source for a diagram illustrating the Document
Object Model hierarchy, showing root element (Document), head, body, and
their respective child elements like title, h1, etc.)
Write a code in JavaScript for any one of the following:
1) To change the background color of the web page automatically after every
5 seconds.

<html>
<head>

Untitled 20
<script type="text/javascript">
function changebgcolor() {
var a = [Link];
// This code toggles the background color between red and yellow.
[Link] = [Link] == "red" ? "yell
ow" : "red";
// The setTimeout function calls changebgcolor again after 5000 mil
liseconds (5 seconds).
setTimeout(changebgcolor, 5000);
}
</script>
</head>
<body onload="changebgcolor()">
<h1>Automatic Background Color Change</h1>
<p>The background color of this page will change automatically every 5
seconds.</p>
</body>
</html>

10) Write a JavaScript code to set a cookie on the user's computer. (5M)
The provided sources do not contain specific JavaScript code for setting a
cookie on the user's computer. While cookies are mentioned as a local storage
mechanism, no code example is given.
Unit 3

React

1) What are components in React? Create


one class component Car and invoke it
using [Link] . (Detailed theory + very
short code)
Detailed definition and explanation (long):
A component in React is a self-contained, reusable unit of UI that encapsulates
its own structure (JSX), behavior (event handlers), and optionally state (data

Untitled 21
that can change over time). Components are the primary building blocks of a
React application — instead of manipulating the DOM directly, you declare what
UI should look like for a given state and React takes care of updating the DOM.
This approach enforces separation of concerns in the UI layer: structure,
styling, and behavior for a particular piece of interface live together in a single
component, which improves maintainability and reusability.
Components come in two broad types:

Class components (ES6 classes extending [Link] ): they can hold


local state, and provide lifecycle methods such as componentDidMount ,
, and componentWillUnmount . Class components are useful when
componentDidUpdate

you need lifecycle hooks or this based state management (legacy apps or
when studying lifecycle concepts).

Function components (plain functions that return JSX): originally stateless,


but with React Hooks ( useState , useEffect , etc.) they can hold state and mimic
lifecycle behaviors. Function components are now the recommended
pattern for new code because they are concise and work well with modern
React patterns.

Why components matter (benefits & concepts):

Reusability: Create once, use many times (e.g., a Button or Modal ).

Composability: Build complex UIs by nesting smaller components (parent


→ child structure).

Encapsulation: Internal implementation (state, helper methods) is hidden;


only public API (props) is used by consumers.

Testability: Smaller pieces are easier to unit-test.

Predictability: With one-way data flow (props down), it’s easier to reason
about how state changes affect the UI.

Props vs State:

Props are read-only inputs passed from parent to child. They make
components configurable and reusable.

State is internal and mutable within a component (for class components,


using [Link] ; for function components, via useState ). State changes
trigger re-renders.

Minimal class component Car (very short, only requested functionality):

Untitled 22
[Link]

import React, { Component } from 'react';

class Car extends Component {


render() {
return <h2>This is a {[Link]} car.</h2>;
}
}

export default Car;

[Link]

import React from 'react';


import ReactDOM from 'react-dom';
import Car from './Car';

[Link](<Car brand="Toyota" />, [Link]('roo


t'));

Short explanation of code: Car is a class component that reads brand from
props and renders a heading. [Link] mounts Car into the DOM element with id
root .

2) What is a Single Page Application


(SPA)? (Detailed theory)
Definition (expanded):
A Single Page Application (SPA) is a web application that loads a single HTML
document and dynamically updates the content on the page as the user
interacts with the app, without performing full page reloads. Instead of the
server returning whole HTML pages for each navigation, the server usually
returns data (JSON) and the client-side JavaScript updates the view. Routing,
view changes, and state management are handled in the browser.

Untitled 23
How SPAs work (architecture):

On first load, the server delivers the static assets — one HTML file,
JavaScript bundles, and CSS.

JavaScript initializes the app, renders the initial UI, and sets up client-side
routing.

When the user navigates, the router intercepts link clicks and updates the
URL and displayed view purely in JavaScript.

Data is fetched asynchronously from the backend (APIs) using


fetch / XMLHttpRequest /Axios, and the UI updates based on API responses.

Key components of SPA architecture:

Client-side router — maps URLs to views (e.g., React Router).

API backend — exposes endpoints for data; the UI requests JSON instead
of full HTML pages.

State management — local component state, context, or external libs


(Redux, Zustand) to hold app-wide data.

Build tools — bundlers like Webpack, Vite, or tools from Create React App
to bundle and optimize assets.

Advantages (detailed):

Smooth UX & Performance: No full reloads → faster perceived navigation


and native-app-like experience.

Reduced Bandwidth Over Time: After initial load, only data (not full pages)
is transferred.

Rich Interactivity: Complex client-side interactions (drag-drop, animations)


are easier.

Decoupled Backend: Backend becomes API-only; same APIs can serve


mobile apps.

Disadvantages and considerations (important exam points):

Initial load time: The JavaScript bundle can be large; must use code-
splitting and lazy loading to improve performance.

SEO & Social Sharing: Historically SPAs had poor SEO because content is
rendered client-side. Solutions: Server-Side Rendering (SSR), Static Site

Untitled 24
Generation (SSG), or hybrid approaches (e.g., [Link]) to pre-render
content for crawlers.

Browser History & Back button: Must be handled explicitly via router to
keep navigation predictable.

Security: Need to protect client-exposed endpoints and handle


authentication carefully (tokens, refresh flows).

Examples: Gmail, Google Maps, many modern web apps (when built with
React, Angular, Vue as SPA front-ends).

3) Explain React Component Life Cycle


with suitable diagram (Detailed theory)
Overview (long):
React class components go through a sequence of lifecycle phases from
creation to destruction. Each phase provides lifecycle methods where you can
run code at predictable times: initialize, fetch data, optimize updates, and clean
up resources. Function components don’t have these methods, but useEffect and
other hooks provide the same capabilities.

Lifecycle phases and methods (detailed):


A. Mounting (component creation and insertion into the DOM)

constructor(props)

Purpose: initialize internal state, bind methods. Keep logic minimal


(avoid heavy side-effects).

Example: [Link] = { items: [] } .

static getDerivedStateFromProps(props, state) (rare)

Purpose: derive state from props before render. Prefer avoiding this
unless necessary.

render()

Purpose: returns JSX describing the UI. Must be pure (no side-effects).

componentDidMount()

Purpose: called once after the component is inserted into the DOM.
Ideal place for AJAX calls, starting subscriptions, setting timers, or DOM

Untitled 25
measurements.

Example: fetch data from API and setState with results.

B. Updating (props or state changes cause re-render)

static getDerivedStateFromProps(nextProps, prevState) (called before every render during


update too)

Purpose: update state in response to prop changes (use sparingly).

shouldComponentUpdate(nextProps, nextState)

Purpose: return true / false to allow or prevent re-rendering. Useful for


performance optimizations (avoid unnecessary renders). Default
returns true . Alternatives: PureComponent or [Link] .

render()

Purpose: update the UI based on current props/state.

getSnapshotBeforeUpdate(prevProps, prevState)

Purpose: capture information from the DOM (e.g., scroll position) before
it is potentially changed by render. Value returned is passed to
componentDidUpdate .

componentDidUpdate(prevProps, prevState, snapshot)

Purpose: perform side-effects after an update (network requests based


on prop changes, DOM updates). Must be careful to avoid infinite loops
when calling setState — conditionally call it.

C. Unmounting (component removal)

componentWillUnmount()

Purpose: cleanup — clear timers, cancel network


requests/subscriptions, remove event listeners to avoid memory leaks.

Lifecycle diagram (exam-friendly ASCII):

Mounting:
constructor()

render()

componentDidMount()

Untitled 26
Updating (on state/props change):
getDerivedStateFromProps()

shouldComponentUpdate()
↓ (if true)
render()

getSnapshotBeforeUpdate()

componentDidUpdate()

Unmounting:
componentWillUnmount()

Practical notes & examples:

Fetch data in componentDidMount so the initial render is fast and DOM exists
when you update state.

Use shouldComponentUpdate or PureComponent when components are expensive to


render.

Always clean up in componentWillUnmount to avoid memory/resource leaks.

With functional components, useEffect with dependency arrays replaces


many lifecycle patterns (e.g., [] = componentDidMount , cleanup function =
componentWillUnmount , dependencies change = componentDidUpdate ).

5) When are React components re-


rendered? Explain giving examples.
(Detailed theory + short code examples)
Detailed explanation of re-rendering (long):
A React component re-renders whenever React determines the UI might need
to change. The main triggers:

Untitled 27
1. State changes inside the component

In class components, calling [Link]() queues a state update that


eventually triggers a re-render (React may batch multiple setState calls).
In function components, calling the setter returned by useState triggers a
re-render of that function component.

2. Props changes received from parent

When a parent component re-renders and passes different prop values


to a child, the child will re-render to reflect the new props. Even if the
prop value is an object/array reference that changed identity (but not
content), that counts as changed.

3. Parent re-render (prop identity not changed)

If a parent re-renders, React will also call the child’s render by default.
This may occur even if the child’s props didn't change. Optimization
techniques (see below) can prevent unnecessary child renders.

4. Context value changes

If a component consumes React Context, it will re-render when the


context value changes.

5. forceUpdate()

forces a re-render — rarely recommended because it


forceUpdate()

bypasses normal update mechanisms.

Important internal process: Reconciliation & Virtual DOM

React performs reconciliation: it computes differences between previous


and current Virtual DOM and applies efficient DOM updates. A re-render
does not necessarily mean the browser DOM will be updated; if the Virtual
DOM output is identical, no DOM patch occurs.

Performance considerations (how to avoid expensive re-renders):

Pure components / [Link]: shallowly compare props and


state to skip re-renders when nothing meaningful changed.

[Link]: wrap function components to memoize them and avoid re-


rendering when props are equal (shallow).

shouldComponentUpdate: implement custom deep or selective


comparisons in class components.

Untitled 28
Keys in lists: correct key usage helps React identify items and avoid re-
rendering entire lists.

Immutable updates: by returning new objects for changed state, you help
shallow comparisons detect changes quickly.

Examples (very short code snippets):

State change (class) — causes re-render

class Counter extends [Link] {


state = { count: 0 };
inc = () => [Link]({ count: [Link] + 1 });
render() { return <button onClick={[Link]}>{[Link]}</button> }
}

Clicking the button updates [Link] → React re-renders Counter .

Props change — child re-renders when parent changes prop

// Parent:
<Child value={[Link].x} />
// If parent does: [Link]({ x: 10 }), Child will receive new prop and re-r
ender.

Parent re-render without prop change (child still renders by default)


To avoid this:

// Functional child
const Child = [Link](({ value }) => <div>{value}</div>);
// Child will skip re-render if `value` is shallowly equal to previous value.

Untitled 29

You might also like