Responsive Design & JavaScript Asynchronous Operations
Responsive Design & JavaScript Asynchronous Operations
1. Explain the concept of Responsive Design using CSS Flexbox. Describe how JavaScript ES6+
Design
Today, websites need to look perfect on every device, whether it's a phone, tablet, or
laptop. This ability to automatically adapt the layout is called Responsive Design. It ensures that
content resizes and reorganizes itself based on the user's screen size.
A responsive website is easy to read, comfortable to use, and does not require
zooming or horizontal scrolling.
Flexbox is a smart CSS layout system that arranges elements automatically within a
container. It simplifies responsive design by ensuring elements adapt to any screen size,
significantly reducing the need for complicated styling rules.
Promises
A Promise is a JavaScript object representing the
eventual completion (or failure) of an
asynchronous operation. It exists in one of three
states:
• Pending: The initial state, where the operation is
still in progress.
• Fulfilled (Resolved): The operation completed
successfully.
• Rejected: The operation failed.
Example of a Promise
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
const success = true; // Simulation
if (success) {
resolve("Data received successfully!");
} else {
reject("Error: Failed to fetch data.");
}
}, 2000);
});
async/await
It simplifies Promise handling by allowing asynchronous logic to be written
in a linear, synchronous style—eliminating the need for complex .then()
chains.
getData();
2. Differentiate between HTML5 Elements and Semantic Tags. Briefly explain the
DOM (Document Object Model) and its purpose in JavaScript manipulation.
HTML5 Elements
HTML5 introduced a robust set of new elements to modernize web development. These
tags go beyond basic structure, offering native support for multimedia, advanced
graphics, and better form controls. While some elements provide semantic meaning (like
<article>), others add powerful functionality (like <video>), significantly reducing the
need for external plugins."
Multimedia & Graphics: Add rich features (e.g., <audio>, <video>, <canvas>)."
Semantic Tags
Semantic tags are a specific subset of HTML5 elements that clearly describe
their meaning to both the browser and the developer. Unlike generic tags
(like <div>), semantic tags explicitly define the purpose of the content they
contain. This improves SEO, boosts accessibility for screen readers, and
makes the code easier to maintain
DOM:
The DOM (Document Object Model) is a programming interface that represents
the structure of a web document. It acts as a bridge between the raw HTML
code and JavaScript. When a browser loads a page, it parses the HTML into a
hierarchical DOM Tree, allowing scripts to dynamically access and manipulate
content, structure, and styles.
DOM Works
Node Conversion:
Every HTML element is parsed and converted into a distinct
Node (object) within the DOM.
Hierarchical Structure:
The DOM organizes these nodes into a
logical Parent-Child Tree structure
Dynamic Manipulation:
This structure allows JavaScript to programmatically access,
modify, append, or remove elements to update the UI
dynamically.
JavaScript can use this structure to access, change, add, or
remove elements on the page.
2. Modify Content & Styles: Dynamically updating text, swapping images, or altering CSS
properties in real-time.
4. Event Handling: Listening and responding to user actions such as clicks, mouse
movements, keyboard inputs, and form submissions.
5. Enhance Interactivity: creating dynamic features like toggle menus, live data updates,
form validation, and smooth animations.
Assignment-03
Props (Properties):
Props are read-only (immutable) data passed from
1 Data Transmission: They serve as the primary mechanism to send data and event
handlers from one component to another.
2 Immutability: Props are read-only; the child component receiving them cannot modify
them, ensuring data stability.
3 Reusability: They make components reusable by allowing the same component structure
to render different data based on what is passed to it.
4 Unidirectional Flow: They enforce a "top-down" data flow, making the application
structure predictable and easier to debug.
5 Configuration: They act like function arguments, allowing parents to configure the
behavior or appearance of child components.
State
State is a built-in object that allows a component to manage its own data
internally. Unlike props, state is mutable and can change over time.
Significance of State
1. Dynamic Data Management: Used to handle data that changes during the
component's lifecycle (e.g., user inputs, counters, toggle switches).
2. Reactivity: When state changes (via useState or setState), React automatically re-
renders the component to reflect the new data in the UI.
3. Interactivity: Enables interactive features like opening/closing modals, form
validation, or live filtering.
4. Optimized Rendering: React is smart enough to update only the specific parts of
the DOM that depend on the changed state.
5. Encapsulation: State makes components "smart" and self-contained, as they
manage their own logic independent of the parent.
6. Makes components self-contained and smart.
Efficient Updates: When an event occurs (like a button click), React efficiently
determines which component needs to update, avoiding unnecessary re-renders of the
entire page.
Memory Optimization: The synthetic event objects are lightweight and are pooled
(reused) by React to keep memory consumption low.
When data changes, React creates a new Virtual DOM tree and compares it
with the previous one (a process called "Diffing") to identify exactly what
changed.
2. Batch Updates
React groups multiple state updates into a single re-render cycle, preventing
the browser from recalculating layout multiple times unnecessarily.
3. Avoids Direct DOM Manipulation Accessing the Real DOM is slow and
expensive. React performs all calculations in the Virtual DOM (which is fast)
and only touches the Real DOM when necessary.
4. Reduces Reflows and Repaints
JSX
JSX (JavaScript XML) is a syntax extension for JavaScript that allows
developers to write HTML-like code directly within JavaScript files. While
browser engines don't understand JSX, React tools (like Babel) compile it
into standard JavaScript objects before rendering.
Why is it important?
• Readability: It makes code visual and easier to understand by keeping logic and UI
together.
Example:
function App () {
return (
<div>
<h1>Hello, this is JSX! </h1>
<p>JSX allows us to write HTML inside JavaScript efficiently.</p>
</div>
);
}
Modern UI/UX design relies on breaking down complex interfaces into smaller,
independent building blocks called Components
1. What is JSX?
Definition: JSX (JavaScript XML) is a syntax extension for JavaScript that allows
developers to write HTML-like code directly within JavaScript files. While browser
engines don't understand JSX, React tools (like Babel) compile it into standard
JavaScript objects before rendering.
Why is it important?
• Readability: It makes code visual and easier to understand by keeping logic and UI
together.
Example:
function App() {
return (
<div>
</div>
);
Modern UI/UX design relies on breaking down complex interfaces into smaller,
independent building blocks called Components.
Shutterstock
Key Benefits:
• Reusability: Write code once and use the same component (like buttons or
navbars) across multiple pages, saving significant development time.
• Maintainability (Isolation): Since each component handles its own logic and
style, fixing a bug in one section doesn't break the entire application.
function Counter() {
// 'count' stores the value, 'setCount' updates it
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}
Q. Define RESTful APIs and explain the basic structure of a [Link] module.
Describe the role of [Link] in middleware and routing.
Ans:
It has become the standard for web services due to its simplicity and scalability.
Definition:
RESTful APIs allow different systems to communicate over the internet using standard
HTTP methods. They treat data as Resources, which are accessed via URLs (Uniform
Resource Locators).
Stateless Nature:
A key characteristic of REST is that it is stateless. This means the server does not store any
state about the client session. Every request must contain all the necessary information
(headers, body, tokens) to be understood and processed
CRUD Operations:
RESTful APIs use HTTP requests to perform CRUD (Create, Read, Update, Delete) actions.
HTTP Methods
Method Type Function
Node Module
• The module Object: Each file has access to a global module object that represents the
current module.
Basic Structure
// Exporting functionality
// Importing functionality
Express
[Link] is a minimalist web framework for [Link]. It simplifies server-side logic effectively
through two main concepts: Middleware and Routing.
Express in middleware
Middleware functions are the backbone of an Express application. They act as "checkpoints"
that a request passes through before reaching the final response
• Modifying request and response objects: For example, parsing JSON data into [Link].
• Calling the next middleware function: Passing control to the next function in the stack using
next().
Express in routing
[Link] provides a robust routing system that allows developers to define how an application
responds to client requests to specific endpoints (URLs) and HTTP methods (GET, POST, PUT,
DELETE, etc.). Key aspects of Express routing include:
• Route parameters: Capturing dynamic values from the URL using colon-prefixed parameters
(e.g., /users/:id).
• Modularity: Using [Link](), developers can create modular route handlers, keeping the
code organized for large applications.
• Query parameters: Accessing data passed in the URL's query string (e.g., ? name=John).
• Route handlers: Functions that execute when a specific route is matched, processing the
request and sending a response.
[Link](3000);
Q. 2 Explain the Event-Driven Architecture of [Link]. Discuss the essential aspects of Error
Handling and Security Considerations when developing backend APIs.
Ans :
Key Components
➢ Events: Signals indicating that a state change has occurred (e.g., "data received", "file
opened")
➢ Event Emitter: Objects that generate (emit) events. Core modules like http and fs inherit
from the EventEmitter class and use .emit() to signal changes
➢ Event Listener Callback functions registered to run when a specific event occurs. They are
attached using methods like .on()
➢ Event Loop The heart of [Link]. It runs on a single thread, continuously monitoring the
event queue and executing callbacks when the main stack is empty.
➢ Non-Blocking I/O Heavy operations (I/O) are offloaded to the system kernel (via the libuv
library) so the main thread remains free to handle other requests.
• Client Request A client sends a request to the server, which is placed in the Event
Queue.
If the task is Asynchronous (I/O, DB query), it is offloaded to the Worker Thread Pool
(managed by libuv).
• Processing:
• If the request involves a time-consuming I/O operation (e.g., reading a large file, network
request), the main thread offloads the task to the thread pool (managed by libuv) and
continues to pick up the next request from the queue.
• Callback Queuing: Once the I/O operation in the thread pool is complete, its associated
callback function is moved to a callback queue.
• Execution: When the main call stack is clear, the event loop pushes callbacks from the
queue onto the stack for execution, and the response is sent back to the client
Proper error handling ensures the API remains reliable and easy to debug without crashing.
• Use Appropriate HTTP Status Codes: Return semantic codes to describe the outcome
clearly.
• Validate Input: Validate data at the entry point. Reject invalid data immediately before it
reaches the database or logic layer.
• Log Errors for Internal Monitoring: Use libraries like Winston or Pino to record errors with
timestamps, request IDs, and user context. This is crucial for debugging post-mortem.
• Centralize Error Handling Logic: Use global middleware (e.g., [Link]((err, req, res, next) =>
{...})) to manage errors in one place, ensuring consistency across the application.
Security Considerations
Security must be a priority to protect user data and server integrity
Authentication: Verify identity using secure standards like OAuth 2.0 or JWT (JSON
Web Tokens).
Authorization: Enforce "Least Privilege" (users can only access what they strictly need).
•Encrypt All Data In Transit: Always use TLS/SSL (HTTPS) to encrypt data moving between
client and server.
At Rest: Encrypt sensitive fields (like passwords) in the database using hashing algorithms (e.g.,
bcrypt).
•Validate and Sanitize All Inputs: This is a primary defense against injection attacks (e.g.,
SQL injection, XSS). Treat all user input as untrusted, validate it against a strict schema, and
sanitize it before it interacts with your backend systems.
•Limit Data Exposure: Only return essential data in API responses. Avoid overexposure of
properties or fields that aren't strictly necessary for the client's use case, as this can leak
sensitive information.
• •Use API Gateways: Implement rate limiting (e.g., max 100 requests per minute) to prevent
DDoS attacks and brute-force attempts. Use an API Gateway to centralize security policies.
Ans :
SQL
Operation Description Example
Command
Registering a new
Create INSERT Adds new records to a table.
user.
SQL
Operation Description Example
Command
• Read: This allows users and applications to access and view stored information. It is used for
searching, filtering, and retrieving data, such as checking an email inbox or viewing a product
page on a website.
• Update: This function is vital for maintaining the accuracy and relevance of stored data over
time. When a user changes their profile picture or edits a message, an "update" operation
modifies the existing data record without deleting and recreating it.
• Delete: This operation manages the data lifecycle by removing outdated, irrelevant, or
unnecessary information. This can be as simple as an email being moved to a trash folder (a
"soft delete", where its status is marked as deleted) or permanently removed from the database
(a "hard delete").
Keys in MySQL
Keys are attributes (or sets of attributes) that uniquely identify rows within a table and define
the relationships between different tables.
1. Primary Key: A column that uniquely identifies every record in a table. It cannot accept
NULL values.
2. Foreign Key: A column that creates a relationship between two tables by pointing to the
Primary Key of another table. It enforces referential integrity.
3. Unique Key: Ensures that all values in a column are distinct. Unlike the Primary Key, it
allows one NULL value (depending on the DB engine).
Example: EmailAddress (Two users cannot have the same email).
4. Composite KeyA key composed of two or more columns to create a unique identifier
when a single column is not enough.
Constraints in MySQL
Constraints are rules enforced on data columns in a table. They are used to limit the type of
data that can go into a table, ensuring the reliability and accuracy of the data.
1. NOT NULL: Ensures that a column cannot have a NULL value. For example, a Username field
should always contain a value.
2. DEFAULT: Provides a default value for a column when no value is specified during an
INSERT operation. (e.g., setting a Status field to 'Active' by default).
3. CHECK: Ensures that all values in a column satisfy specific conditions. For example,
ensuring that an Age column only accepts values greater than 18.
Q. 2. What are Joins in SQL? Give an example of a situation where you would use a
Transaction to maintain data integrity. Describe how Database Connectivity is established
using backend frameworks.
Ans :
JOIN IN SQL: SQL Joins are used to combine rows from two or more tables based on a related
column (typically a Primary Key and Foreign Key relationship). They allow us to query data
scattered across multiple normalized tables.
Joins in SQL are used to combine rows from two or more tables based on a related column
between them.
They help retrieve data that is spread across multiple tables in a relational database.
Common Types of Joins:
INNER JOIN: Returns records that have matching values in both tables.
LEFT JOIN: Returns all records from the left table and matched records from the right.
RIGHT JOIN: Returns all records from the right table and matched records from the left.
Example ([Link]):
// Create connection
const connection = [Link]({
host: 'localhost',
user: 'root',
password: 'password123',
database: 'my_database'
});
// Connect
[Link]((err) => {
if (err) throw err;
[Link]('Connected to MySQL Database!');
});