0% found this document useful (0 votes)
4 views47 pages

Full Stack Development Bis601: Module 1: Javascript Basics

The document covers important questions related to Full Stack Development, specifically focusing on JavaScript basics and DOM manipulation. It includes explanations of data types, control structures, functions, and event handling in JavaScript, along with examples and code snippets. Additionally, it discusses the Document Object Model (DOM), event listeners, and methods for updating element attributes.

Uploaded by

abendisagar
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)
4 views47 pages

Full Stack Development Bis601: Module 1: Javascript Basics

The document covers important questions related to Full Stack Development, specifically focusing on JavaScript basics and DOM manipulation. It includes explanations of data types, control structures, functions, and event handling in JavaScript, along with examples and code snippets. Additionally, it discusses the Document Object Model (DOM), event listeners, and methods for updating element attributes.

Uploaded by

abendisagar
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
You are on page 1/ 47

IMPORTANT QUESTIONS

Full Stack Development BIS601

Module 1: JavaScript Basics


Q.1 Explain different data types in JavaScript with suitable examples.
In JavaScript, each value has a data type, defining its nature (e.g., Number, String, Boolean) and
operations. Data types are categorized into Primitive (e.g., String, Number) and Non-Primitive (e.g.,
Objects, Arrays).
Primitive Data Type
1. Number : Represents both integers and floating-point numbers.
let age = 30; // Integer
let price = 19.99; // Floating-point

2. String: Represents textual data, enclosed in single quotes, double quotes, or backticks (template
literals).
let name = "Alice"; // Double quotes
let greeting = 'Hello!'; // Single quotes
let message = `My name is ${name}.`; // Template literal

3. Boolean: Represents a logical entity and can only have two values: true or false.
let isActive = true;
let hasPermission = false;

4. Undefined: Indicates that a variable has been declared but has not yet been assigned a value.
let myVariable; // myVariable is undefined

5. Null: Represents the intentional absence of any object value. It's a primitive value.
let emptyValue = null;

6. Symbol: Introduced in ES6, it represents a unique and immutable value, often used as object
property keys to avoid naming collisions.
const id = Symbol('uniqueId');
7. BigInt: Introduced in ES2020, it represents integers with arbitrary precision, allowing for
numbers larger than the maximum safe integer for Number.
JavaScript
let bigNumber = 9007199254740991n; // The 'n' indicates a BigInt

Non-Primitive (Reference) Data Types


These store collections or functions.
1. Object
Used to store key-value pairs.
let student = {
name: "Deepika",
age: 22,
course: "MERN Stack"
};
console.log(student.name, student.age);
2. Array
Stores multiple values in a single variable.
let colors = ["Red", "Green", "Blue"];
console.log(colors[0]); // Output: Red
3. Function
A block of reusable code.
function greet() {
return "Hello, JavaScript!";
}
console.log(greet());

Q.2 Write a JavaScript program using loops and conditions to print prime numbers
between 1 and 100.

// JavaScript program to print prime numbers between 1 and 100


for (let num = 2; num <= 100; num++) {
let isPrime = true;
// Check if num is divisible by any number from 2 to sqrt(num)
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
isPrime = false;
break;
}
}
// Print the number if it is prime
if (isPrime) {
console.log(num);
}
}

Q.3 Differentiate between var, let, and const with examples

Var let const

The scope of a varvariable is The scope of alet variable is The scope of a const variable is
functional or global scope. block scope. block scope.

It can be updated but cannot


It can be updated and re- It can neither be updated or
be re-declared in the same
declared in the same scope. re-declared in any scope.
scope.

It can be declared without It can be declared without It cannot be declared without


initialization. initialization. initialization.

It can be accessed without It cannot be accessed without It cannot be accessed without


initialization as its default initialization otherwise it will initialization, as it cannot be
value is "undefined". give 'referenceError'. declared without initialization.

These variables are hoisted but These variables are hoisted but
These variables are hoisted. stay in the temporal dead zone stays in the temporal dead
untill the initialization. zone until the initialization.

Q.4 Create a function in JavaScript to sort an array of strings alphabetically


function sortStringsAlphabetically(arr) {
return arr.sort();
}
// Example usage:
const fruits = ["Banana", "Apple", "Mango", "Grapes", "Orange"];
const sortedFruits = sortStringsAlphabetically(fruits);

console.log(sortedFruits);

Q.5 What are JavaScript objects? Create a custom object and demonstrate object
methods.

JavaScript objects are non-primitive data types used to store collections of data as key-value pairs. These
pairs consist of properties (variables) and methods (functions) that define the object's characteristics and
behaviors. Objects are fundamental building blocks in JavaScript, allowing for the organization and
encapsulation of related data and functionality.

Custom Object and Methods Demonstration:


const Car = {
make: "Toyota",
model: "Camry",
year: 2023,

startEngine: function() {
console.log("The engine is starting...");
},
displayInfo: function() {
console.log(`Make: ${this.make}, Model: ${this.model}, Year: ${this.year}`);
}
};
console.log(Car.make);
Car.startEngine();
Car.displayInfo();

Q.6 Write a program to demonstrate string operations like slicing, concatenation, and
replacement

// Original strings
let str1 = "Hello";
let str2 = "World";

// 1. Concatenation
let fullStr = str1 + " " + str2;
console.log("Concatenation:", fullStr); // Output: Hello World

// 2. Slicing (substring extraction)


let sliced = fullStr.slice(0, 5); // from index 0 to 4
console.log("Sliced (0 to 5):", sliced); // Output: Hello

// 3. Replacement
let replaced = fullStr.replace("World", "JavaScript");
console.log("After Replacement:", replaced); // Output: Hello JavaScript

// Additional: String Length


console.log("Length of string:", fullStr.length); // Output: 11

// Additional: Uppercase and Lowercase


console.log("Uppercase:", fullStr.toUpperCase()); // HELLO WORLD
console.log("Lowercase:", fullStr.toLowerCase()); // hello world

Q.7 Discuss the role and syntax of comments, statements, and expressions in JavaScript

In JavaScript, comments, statements, and expressions serve distinct roles in code organization, execution,
and value generation.
1. Comments:
Comments are non-executable parts of the code used to provide explanations, documentation, or temporarily
disable code sections. They are ignored by the JavaScript engine during execution.
Syntax:
Single-line comments: Begin with //. All text from // to the end of the line is a comment.
// This is a single-line comment
let x = 10; // Assigning a value to x

Multi-line (block) comments: Begin with /* and end with */. All text between these delimiters, spanning
multiple lines, is a comment.
/*
This is a multi-line comment.
It can span across several lines
to provide detailed explanations.
*/
2. Statements:
Statements are instructions that perform an action. They represent a complete unit of execution in
JavaScript.
Syntax:
Statements typically end with a semicolon (;), although in many cases, Automatic Semicolon Insertion (ASI)
can infer them.
let name = "John"; // Variable declaration and assignment statement
console.log(name); // Function call statement
if (true) { // Conditional statement
// ...
}
for (let i = 0; i < 5; i++) { // Loop statement
// ...
}

3. Expressions:
Expressions are combinations of values, variables, and operators that evaluate to a single value. They can be
part of a larger statement.
Syntax:
Expressions do not necessarily end with a semicolon unless they also function as a standalone statement.
5 + 3 // An arithmetic expression evaluating to 8
"Hello" + " " + "World" // A string concatenation expression
x > 5 // A comparison expression evaluating to true or false
let result = (a * b) / c; // The part (a * b) / c is an expression
Q.8 Design a calculator program that uses functions to perform basic operations (+, –,
×, ÷).

function add(a, b) { function add(a, b) {


return a + b; return a + b;
} }
function subtract(a, b) { function subtract(a, b) {
return a - b; return a - b;
} }
function multiply(a, b) { function multiply(a, b) {
return a * b; return a * b;
} }
function divide(a, b) { function divide(a, b) {
if (b === 0) { if (b === 0) {
throw new Error("Division by zero is not throw new Error("Division by zero is not allowed");
allowed"); }
} return a / b;
return a / b; }
} function calculator() {
function calculator() { const num1 = parseFloat(prompt("Enter first
const num1 = parseFloat(prompt("Enter first number:"));
number:")); const operator = prompt("Enter operator (+, -, *, /):");
const operator = prompt("Enter operator (+,
-, *, /):"); const num2 = parseFloat(prompt("Enter second
number:"));
const num2 = parseFloat(prompt("Enter if (isNaN(num1) || isNaN(num2)) {
second number:")); return "Invalid number input!";
if (isNaN(num1) || isNaN(num2)) { }
return "Invalid number input!";
} try {
switch (operator) {
try { case '+':
switch (operator) { return add(num1, num2);
case '+': case '-':
return add(num1, num2); return subtract(num1, num2);
case '-': case '*':
return subtract(num1, num2); return multiply(num1, num2);
case '*': case '/':
return multiply(num1, num2); return divide(num1, num2);
case '/': default:
return divide(num1, num2); return "Invalid operator!";
default: }
return "Invalid operator!"; } catch (error) {
} return error.message;
} catch (error) { }
return error.message; }
} const result = calculator();
} console.log("Result:", result);
const result = calculator();
console.log("Result:", result);
Module 2: DOM & Events

Q.1 Explain the Document Object Model (DOM) and its tree structure

The Document Object Model (DOM) is a programming interface that represents an HTML or XML
document as a tree structure, allowing scripts (like JavaScript) to dynamically access and manipulate the
document's content, structure, and style. In essence, the DOM treats each part of a webpage as a node in a
tree, enabling developers to interact with and modify the page's elements.

Here's a breakdown of the DOM and its tree structure:


What the DOM is:
A programming interface:
The DOM provides a set of rules and methods for interacting with web page content.
Represents a document as a tree:
The DOM transforms an HTML or XML document into a hierarchical tree-like structure.
Allows dynamic manipulation:
This tree structure enables JavaScript (or other scripting languages) to modify the webpage's content,
structure, and style.

The DOM Tree Structure:


Root Node: The entire document (e.g., an HTML page) is the root node of the DOM tree.
Nodes: Each element, attribute, and text within the document becomes a node in the tree.
Hierarchical Relationships: Nodes are arranged in a parent-child relationship, forming a tree.
Example: In an HTML document, the <html> element is typically the root's child, and it can have <head>
and <body> elements as children, and so on.
Leaf Nodes: Text within elements, such as the text content of a paragraph, is represented as leaf nodes
(node with no children)
Ex :
<!DOCTYPE html> DOM Tree
<html>
└── html
<head>
<title>My Page</title> ├── head

</head> │ └── title


<body> │ └── "My Page"
<h1>Hello World</h1> └── body
<p>This is a
├── h1
paragraph.</p>
Q.2 Write JavaScript code to select an element and change its content dynamically

<!DOCTYPE html>
<html>
<head>
<title>Dynamic Content</title>
</head>
<body>
<h1 id="greeting">Hello!</h1>
<button onclick="changeContent()">Click Me</button>
<script>
function changeContent() {
const heading = document.getElementById("greeting");
heading.textContent = "Welcome to JavaScript DOM!";
}
</script>
</body>
</html>

Q.3 What are event listeners? Create an example using addEventListener() for a button
click.
In JavaScript, event listeners are functions that wait for user interactions like clicks, key presses, mouse
moves, etc., and then execute code in response.

Using addEventListener(), we can attach multiple actions to a single element and separate JavaScript
from HTML — keeping code clean and organized.

Syntax: element.addEventListener("eventType", function);

<!DOCTYPE html>
<html>
<head>
<title>Event Listener Example</title>
</head>
<body>
<button id="myButton">Click Me</button>
<p id="message">Initial message</p>

<script>
const button = document.getElementById("myButton");
const message = document.getElementById("message");
button.addEventListener("click", function() {
message.textContent = "You clicked the button!";
});
</script>
</body>
</html>

Q.4 Describe the differences between event delegation and direct event binding.

Feature Direct Event Binding Event Delegation

Number of One listener per element One listener for multiple elements
Listeners

Dynamic Requires re-binding for new elements Handles new elements automatically through
Content bubbling

Performance Can be less efficient with many More efficient with many elements and dynamic
elements content

Code Clarity Can be more verbose with many Can be more concise with many elements
elements

Example element.addEventListener('click', document.addEventListener('click', 'selector',


function() { ... }); function(event) { ... });

Advantages Simplicity , Precise Targeting, Less Memory Usage , Performance Boost , Works
Better for Non-Bubbling Events with Dynamic Elements, Easier Maintenance
Disadvantages Doesn't Handle Dynamic Elements, More Complex Logic, Not Suitable for All Events,
Scalability Problems, Memory Usage Unexpected Behavior

Q.5 Explain how to update element attributes using JavaScript

To add/update an attribute to an HTML element using JavaScript, we have multiple


approaches. In this article, we are going to learn how to add/update an attribute to an HTML
element using JavaScript.
1. Using setAttribute() Method:
The setAttribute() method is a versatile way to add or modify any attribute of an
HTML element. It takes two arguments: the name of the attribute as a string, and the new
value for that attribute, also as a string.

<img id="myImage" src="old.jpg" alt="Old Image">


<script>
const img = document.getElementById("myImage");
img.setAttribute("src", "new.jpg");
img.setAttribute("alt", "New Image");
</script>

2. Direct Property Access:


For common HTML attributes that have corresponding properties on the DOM
element object , you can directly access and modify them as properties.

<a id="myLink" href="https://old.com">Old Link</a>


<script>
const link = document.getElementById("myLink");
link.href = "https://new.com";
link.textContent = "New Link";
</script>

Q.6 Discuss various types of browser events with examples.


1. Mouse Events

click: Occurs when the user clicks an element. For example, if a button is clicked, the click
event will fire.
mouseover / mouseout: Fires when the mouse cursor enters or leaves the boundaries of an
element, respectively.
mousedown / mouseup: Fired when the mouse button is pressed down or released over an
element.
mousemove: Fired when the mouse is moved over an element.
contextmenu: Fires when the user right-clicks on an element, typically opening a context
menu.
Ex: document.getElementById("btn").addEventListener("click", function() {
alert("Button clicked!");
});

2. Keyboard Events:
keydown / keyup: Triggered when a key is pressed down or released, respectively.
Ex: document.addEventListener("keydown", function(event) {
console.log("Key pressed:", event.key);
});

3. Form Events:
submit: Fired when a form is submitted (e.g., by clicking a submit button).
focus / blur: Fired when an element gains or loses focus, respectively (e.g., when a user
clicks inside or outside an input field).
change: Fires when the value of an element (like an input field) is changed.
Ex: document.querySelector("form").addEventListener("submit", function(e) {
e.preventDefault();
alert("Form submitted!");
});
4. Window Events:
load: Fires when the entire page (including all resources like images) has finished loading.
DOMContentLoaded: Fires when the HTML document has been completely loaded and
parsed, but external resources might still be loading.
resize: Fires when the browser window is resized.
scroll: Fires when the document is scrolled.
hashchange: Fires when the URL's fragment identifier (the part after the #) has changed.
unload: Fires when the user is navigating away from the page (e.g., closing the tab or
navigating to a different page).
Ex: window.addEventListener("resize", function() {
console.log("Window resized!");
});

Q.7 Implement a script that changes the background color of a page on a mouseover
event

To change the background color of a page on a mouseover event using JavaScript, you can
use the onmouseover event and the document.body.style.backgroundColor property.
<!DOCTYPE html>
<html>
<head>
<title>Background Color Changer</title>
</head>
<body onmouseover="changeBackgroundColor('red')"
onmouseout="changeBackgroundColor('white')">
<h1>Move your mouse over me</h1>
<p>This page's background color will change when you move your mouse over it.</p>
<script>
function changeBackgroundColor(color) {
document.body.style.backgroundColor = color;
}
</script>
</body>
</html>
Q.8 Write code that listens for keyboard input and logs the key pressed

<!DOCTYPE html>
<html>
<head>
<title>Key Logger</title>
</head>
<body>
<h2>Press any key</h2>
<div id="output"></div>
<script>
const output = document.getElementById('output');
document.addEventListener('keydown', (e) => {
output.innerHTML = `
Key: <b>${e.key}</b><br>
Code: ${e.code}<br>
Ctrl: ${e.ctrlKey ? 'Yes' : 'No'}<br>
Shift: ${e.shiftKey ? 'Yes' : 'No'}
`;
console.log('Pressed:', e.key);
});
</script>
</body>
</html>

This version shows:


The key pressed
The physical key code
Whether Ctrl/Shift were held down
Module 3: Forms, React Basics & MERN Intro
Q.1 Describe the importance of form validation and write a simple form with client-
side validation.
Form validation is crucial for ensuring data accuracy, enhancing security, and improving user
experience by providing immediate feedback on input errors. Client-side validation, in particular, offers the
advantage of instant feedback to the user as it's processed in the browser before submission. This prevents
unnecessary server requests and improves the overall user experience by reducing delays
It's important:
1. Data Quality: Ensures users provide information in the correct format
2. User Experience: Provides immediate feedback when errors occur
3. Security: Prevents malicious data submission that could compromise your system
4. Efficiency: Reduces server load by catching errors client-side before submission
5. Accessibility: Helps users with disabilities understand input requirements
<!DOCTYPE html>
<html>
<head>
<title>Form Validation Example</title>
</head>
<body>
<h2>Registration Form</h2>
<form id="registrationForm" onsubmit="return validateForm()">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email"><br><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
let name = document.getElementById("name").value;
Q.2 Explain the MERN stack architecture with a brief role of each component

The MERN stack is a popular JavaScript-based web development framework for building dynamic and
scalable web applications. It consists of four key technologies: MongoDB, Express.js, React, and
Node.js. MongoDB is the database, Express.js is the backend framework, React is the frontend library, and
Node.js provides the runtime environment for the backend.

1. MongoDB (Database Layer) : NoSQL database for data storage


 Document-oriented database that stores data in flexible, JSON-like documents
 Schema-less design allows for easy modification of data structure
 Highly scalable with good performance for read/write operations
 Uses BSON (Binary JSON) format for data storage
 Provides features like indexing, replication, and sharding
2. Express.js (Backend/Server Layer) : Web application framework for Node.js
 Handles server-side logic and API routes
 Middleware architecture for handling HTTP requests/responses
 Simplifies routing, session management, and authentication
 Integrates with MongoDB through libraries like Mongoose
 Lightweight and flexible compared to more opinionated frameworks
3. React.js (Frontend/View Layer): JavaScript library for building user interfaces
 Creates dynamic, component-based UIs with virtual DOM for efficient rendering
 Handles the presentation layer and user interactions
 Communicates with backend via API calls (typically REST or GraphQL)
 Supports state management (with Context API, Redux, etc.)
 Enables single-page application (SPA) development
4. Node.js (Runtime Environment): JavaScript runtime for server-side execution
 Provides the environment to run Express.js server
 Handles asynchronous I/O operations efficiently
 Uses event-driven, non-blocking architecture
 Manages connections to database and other services
 Serves the React application and API endpoints

MERN Data Flow:


1. User Interaction and Front-End (React):
 The user interacts with the application through a React-based user interface.
 When a user submits data (e.g., through a form), React captures this data and prepares it for
transmission.
 This data is typically sent to the backend via HTTP requests, often using tools like fetch or
Axios.
2. Backend (Node.js and Express.js):
 The Express.js server receives the request from the front-end.
 Express.js handles routing requests, validating data, and performing any necessary business
logic.
 The server interacts with the MongoDB database (using Mongoose or a similar library) to
read, write, or update data.
 After processing, the server sends a response back to React.
3. Database (MongoDB):
 MongoDB stores the application's data.
 It's a NoSQL database that stores data in flexible, JSON-like documents, which aligns well
with the data structures used in React and Node.js.
4. React (Front-End Update):
 React receives the response from the server.
 Based on the response, React updates the user interface, displaying the results to the user or
confirming the action

Q. 3 Write a React component to display a list of tasks with props.

import React from 'react'; Parent Component:


function TaskList({ tasks }) {
return ( import React from 'react';
<div> import TaskList from './TaskList'; function App() {
<h2>Task List</h2> const myTasks = [
{tasks.length > 0 ? ( { id: 1, text: 'Buy groceries', completed: false },
<ul> { id: 2, text: 'Clean the house', completed: true },
{tasks.map(task => ( { id: 3, text: 'Walk the dog', completed: false },
];
<li key={task.id}>
return (
{task.text} {task.completed ?
<div>
'(Completed)' : ''} <h1>My Application</h1>
</li> <TaskList tasks={myTasks} />
))} <TaskList tasks={[]} /> {/* Example with an
</ul> empty task list */}
):( </div>
<p>No tasks to display.</p> );
)} }
</div>
); export default App;
}
export default TaskList;
Q.4 Differentiate between class-based and functional components in React.

Feature Functional Components Class Components

State It can use Hooks like


It uses this.state and this.setState()
Management useState, useReducer

It uses traditional lifecycle methods like


It uses useEffect Hook for
Lifecycle componentDidMount,
lifecycle methods
Methods componentWillUnmount

Returns JSX directly inside


Uses a render() method to return JSX
Rendering the function

Faster and more lightweight Slightly heavier due to the overhead of


Performance due to simpler structure class instances

Can use React hooks Cannot use hooks; relies on lifecycle


Hooks (useState, useEffect, etc.) methods and state

This Keyword Does not use this keyword Uses this to access props and state

Code Less boilerplate code, easier More boilerplate code, especially for state
Complexity to write and understand and methods
Feature Functional Components Class Components

Event Simple and direct event Requires method binding for event
Handling handling handling

Syntax Uses ES6 classes Uses plain JavaScript functions

Q.5 Create a simple issue tracker using component composition and static data.

Issue.js :

import React from 'react';


import IssueTracker from './components/IssueTracker';

const App = () => {


const issues = [
{ id: 1, title: "Login button not responsive", status: "Open" },
{ id: 2, title: "Unable to fetch user profile", status: "In Progress" },
{ id: 3, title: "Typo in homepage header", status: "Closed" },
];

return (
<div style={{ padding: '20px', fontFamily: 'Arial' }}>
<h1>� Issue Tracker</h1>
<IssueTracker issues={issues} />
</div>
);
};
export default App;

IssueTracker.js :

import React from 'react';


import IssueItem from './IssueItem';
const IssueTracker = ({ issues }) => {
return (
<div>
{issues.map(issue => (
<IssueItem key={issue.id} issue={issue} />
))}
</div>
);
};
export default IssueTracker;

IssueItem.js:

import React from 'react';

const IssueItem = ({ issue }) => {


const { title, status } = issue;
const color = status === "Open" ? "red" : status === "In Progress" ? "orange" : "green";

return (
<div style={{
border: '1px solid #ccc',
padding: '10px',
margin: '8px 0',
borderRadius: '5px'
}}>
<h3>{title}</h3>
<p>Status: <span style={{ color }}>{status}</span></p>
</div>
);
};

export default IssueItem;

Q.6 What are children props? Demonstrate passing data using children.
In React, children is a special prop that allows you to pass components or elements as content to other
components, effectively nesting structures and enabling component composition. This special prop allows
for creating more flexible and reusable components, where the parent component can define the structure
while the child component provides the specific content.

// Parent Component
function ParentComponent({ children }) {
return (
<div style={{ border: '1px solid black', padding: '10px' }}>
{children}
</div>
);
}

// Child Component
function MyComponent({ text }) {
return <p>{text}</p>;
}

// Usage
function App() {
return (
<ParentComponent>
<MyComponent text="This is some content from the child." />
<p>This is some text passed directly.</p>
</ParentComponent>
);
}

export default App;

Q.7 Design a React component that conditionally renders content based on a boolean
prop.

A React component can conditionally render content based on a boolean prop using various methods,
including the ternary operator, logical AND operator, or an if statement.
i. Ternary Operator:

import React from 'react';

function ConditionalContent({ showContent }) {


return (
<div>
{showContent ? (
<p>This content is shown when 'showContent' is true.</p>
):(
<p>This content is shown when 'showContent' is false.</p>
)}
</div>
);
}

export default ConditionalContent;

ii. Logical AND Operator (&&):

import React from 'react';


function OnlyShowIfTrue({ showContent }) {
return (
<div>
{showContent && <p>This content only appears when 'showContent' is true.</p>}
</div>
);
}
export default OnlyShowIfTrue;

iii. if statement:
import React from 'react';
function ComplexConditionalContent({ isLoggedIn, isAdmin }) {
if (isLoggedIn && isAdmin) {
return <p>Welcome, Admin!</p>;
} else if (isLoggedIn) {
return <p>Welcome, User!</p>;
} else {
return <p>Please log in.</p>;
}
}
export default ComplexConditionalContent;

Q.8 Write a Hello World MERN setup explanation with a minimal code base

Here's a minimal ―Hello World‖ MERN stack setup explained simply — with just enough to
show how all four parts (MongoDB, Express, React, Node.js) work together.

a. index.js:

const express = require('express');


const cors = require('cors');
const app = express();
const PORT = 5000;
app.use(cors());
app.get('/api/hello', (req, res) => {
res.json({ message: "Hello from Express + Node!" });
});
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});

b. client.js:
import React, { useEffect, useState } from 'react';
function App() {
const [msg, setMsg] = useState('');
useEffect(() => {
fetch('http://localhost:5000/api/hello')
.then(res => res.json())
.then(data => setMsg(data.message));
}, []);
return (
<div style={{ fontFamily: 'Arial', padding: '20px' }}>
<h1>� MERN Hello World</h1>
<p>{msg}</p>
</div>
);
}

export default App;

 Connect MongoDB:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/helloDB')
.then(() => console.log("MongoDB connected"))
.catch(err => console.log(err));
Module 4: React State & API (Express, GraphQL)

Q.1 Define React state and explain how to initialize and update it.

In React, state is a JavaScript object that holds data specific to a component, which can change over time
and influence the component's rendering. When the state of a component changes, React automatically re-
renders that component and its children to reflect the updated data in the UI. This makes React components
dynamic and responsive to user interactions or data updates.

Initializing State:
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
}

Class Components (in the constructor):


import React from 'react';

class Car extends React.Component {


constructor(props) {
super(props);
this.state = { brand: 'Ford', year: 2023 }; }
}

Updating State:
setCount(count + 1);

setCount(prevCount => prevCount + 1);

Class Components (using this.setState()):

this.setState({ brand: 'Chevrolet' });

this.setState((prevState, props) => ({


year: prevState.year + 1
}));

Key Points About State


1. Immutable Updates: Always create new state objects/arrays rather than modifying
existing ones
2. Asynchronous Updates: State updates may be batched, so don't rely on immediate
changes
3. Merge Behavior: In class components, setState merges objects; in hooks, you need to
manually merge
4. Initialization: State is typically initialized when the component mounts

Q.2 Implement a React component using useState and useEffect for counter behavior.

import React, { useState, useEffect } from 'react';

function Counter() {
const [count, setCount] = useState(0);

useEffect(() => {
console.log(`Counter updated: ${count}`);
document.title = `Count: ${count}`;
}, [count]);

return (
<div style={{ fontFamily: 'Arial', textAlign: 'center', marginTop: '50px' }}>
<h1>� React Counter</h1>
<p>Current count: {count}</p>
<button onClick={() => setCount(count + 1)} style={{ marginRight: '10px' }}>
Increment
</button>
<button onClick={() => setCount(count - 1)}>
Decrement
</button>
</div>
);
}

export default Counter;


Q.3 Explain the concept of "lifting state up" in React with an example

"Lifting state up" in React is a pattern used to share state between multiple components that
need to access and potentially modify the same data. Instead of each component managing
its own independent state, the shared state is moved ("lifted") to their closest common
ancestor component. This ancestor then becomes the "single source of truth" for that state.
Concept:
 Identify Shared State:
Determine which components require access to the same piece of state data.
 Move State to Common Ancestor:
Locate the closest parent component that is an ancestor to all components needing the shared
state. Declare and manage the state within this common ancestor.
 Pass State Down as Props:
The common ancestor passes the state values down to its relevant child components as props.
 Handle State Changes with Callbacks:
If a child component needs to update the shared state, the common ancestor passes down
callback functions as props. The child component invokes these callbacks, passing the
necessary data, which then allows the common ancestor to update its state.

Example:
A.js
import React, { useState } from 'react';
import NameInput from './NameInput';
import NameDisplay from './NameDisplay';

function App() {
const [name, setName] = useState('');

return (
<div style={{ fontFamily: 'Arial', padding: '20px' }}>
<h1> Lifting State Up Example</h1>
<NameInput name={name} setName={setName} />
<NameDisplay name={name} />
</div>
);
}
export default App;

B.js:

import React from 'react';


const NameInput = ({ name, setName }) => {
return (
<div>
<input
type="text"
value={name}
placeholder="Enter your name"
onChange={(e) => setName(e.target.value)}
/>
</div>
);
};
export default NameInput;

C.js:
import React from 'react';

const NameDisplay = ({ name }) => {


return (
<p>� Hello, {name || 'stranger'}!</p>
);
};
export default NameDisplay;

Q.4 Compare state vs props with a real-world analogy.

PROPS STATE

The Data is passed from one


The Data is passed within the component only.
component to another.

It is Immutable (cannot be
It is Mutable ( can be modified).
modified).

Props can be used with state and The state can be used only with the state
functional components. components/class component (Before 16.0).

Props are read-only. The state is both read and write.

Q.5 What is a GraphQL schema? Illustrate with a simple example.

A GraphQL Schema serves as a blueprint for the API that defines what data can be queried
from the server, and what are the different types of that data. They define a contract of API
between a server and a client.

Ex:

type Post {
id: ID!
title: String!
content: String!
author: String!
}
type Query {
getPost(id: ID!): Post
listPosts: [Post]
}

type Mutation {
createPost(title: String!, content: String!, author: String!): Post
}

Q.6 Write a sample Express.js REST API to create and fetch product data

A sample Express.js REST API for creating and fetching product data is provided
below. This example uses an in-memory array to simulate a database

const express = require('express');


const bodyParser = require('body-parser');
const app = express();
const PORT = 3000;

let products = [];


let nextProductId = 1;

app.use(bodyParser.json());

app.post('/products', (req, res) => {


const { name, price, description } = req.body;

if (!name || !price) {
return res.status(400).json({ message: 'Product name and price are required.' });
}

const newProduct = {
id: nextProductId++,
name,
price,
description: description || '' // Optional description
};

products.push(newProduct);
res.status(201).json(newProduct); // 201 Created
});

app.get('/products', (req, res) => {


res.status(200).json(products);
});

app.get('/products/:id', (req, res) => {


const productId = parseInt(req.params.id);
const product = products.find(p => p.id === productId);

if (!product) {
return res.status(404).json({ message: 'Product not found.' }); // 404 Not Found
}

res.status(200).json(product);
});

app.listen(PORT, () => {
console.log(`Product API running on http://localhost:${PORT}`);
});

Q.7 Discuss GraphQL vs REST architecture.


Feature REST GraphQL
Data Fetching Multiple endpoints, often Single endpoint, fetch exactly
overfetch/underfetch what you need
Endpoint One endpoint per resource (e.g., Single /graphql endpoint
Structure /users, /posts)
Data Format JSON (usually) JSON (always)
Query Language None – uses HTTP methods (GET, Uses its own query language
POST, etc.) (GraphQL syntax)
Versioning Requires versioning (/v1/users, No versioning needed – clients
/v2/users) define needed data
Flexibility Fixed response structure Highly flexible, client specifies
fields
Nested Data Requires multiple requests or joins Easily supports nested
relationships in one query
Error Handling HTTP status codes Error messages inside a successful
JSON response
Performance Can result in over-fetching (extra Reduces over-fetching by
data) specifying exact fields

Q.8 Design an Express API that validates inputs and handles errors gracefully.

1. Input Validation with express-validator


npm install express-validator

a) Validation Middleware:

const { body, validationResult } = require('express-validator');

const validateUser = [
body('username')
. isLength({ min: 3 })
.withMessage('Username must be at least 3 characters long'),
body('email')
.isEmail()
.withMessage('Invalid email address'),
body('password')
.isStrongPassword()
.withMessage('Password is not strong enough'),
(req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
next();
}
];

Apply to Routes:

app.post('/users', validateUser, (req, res) => {


// Process valid user data
res.status(201).send('User created successfully');
});

2. Centralized Error Handling:

a) Error Handling Middleware:


app.use((err, req, res, next) => {
console.error(err.stack);
if (err.name === 'ValidationError') {
return res.status(400).json({ message: err.message });
}
res.status(500).json({ message: 'Something went wrong!' });
});

b) Propagate Errors:
app.get('/data', async (req, res, next) => {
try {
const data = await fetchDataFromDatabase();
res.json(data);
} catch (error) {
next(error);
}
});
Module 5: MongoDB, Webpack & Modularization

Q.1 Explain the core components of MongoDB: Document, Collection, and Database.
 MongoDB - Database, Collection, and Document

 Document in MongoDB:
In MongoDB, the data records are stored as BSON documents. Here, BSON stands for
binary representation of JSON documents, although BSON contains more data types as
compared to JSON. The document is created using field-value pairs or key-value
pairs and the value of the field can be of any BSON type.

Syntax:
{
field1: value1
field2: value2
....
fieldN: valueN
}
Document Structure:
A document in MongoDB is a flexible data structure made up of field-value pairs. For
instance:
{
title: "MongoDB Basics",
author: "John Doe",
year: 2025
}
Naming restriction for Document Fields:
Before moving further first you should learn about the naming restrictions for fields:
 Fields in documents must be named with strings
 The _id field name is reserved to use as a primary key. And the value of this field must
be unique, immutable, and can be of any type other than an array.
 The field name cannot contain null characters.
 The top-level field names should not start with a dollar sign ($).
Document Size:
The maximum size of the BSON document is 16MB. It ensures that the single document
does not use too much amount of RAM or bandwidth(during transmission). If a document
contains more data than the specified size, then MongoDB provides a GridFS API to store
such type of documents. A single document may contain duplicate fields.
MongoDB always saves the order of the fields in the documents except for the _id field
(which always comes in the first place) and the renaming of fields may change the order
of the fields in the documents.

 Collection in MongoDB:
A Collection in MongoDB is similar to a table in relational databases. It holds a group of documents
and is a part of a database. Collections provide structure to data, but like the rest of MongoDB, they
are schema-less.
Schemaless
As we know that MongoDB databases are schemaless. So, it is not necessary in a collection that
the schema of one document is similar to another document. Or in other words, a single collection
contains different types of documents like as shown in the below example
where mystudentData collection contain two different types of documents:

Multiple Collections per Database


A single database can contain multiple collections, each storing different types of documents.

Naming Restrictions for Collection:


Before creating a collection we should first learn about the naming restrictions for collections:
 Collection name must starts with an underscore (`_`) or a letter (a-z or A-Z)
 Collection name should not start with a number, and does not contain $, empty string, null character
and does not begin with prefix `system.` as this is reserved for MongoDB system collections.
 The maximum length of the collection name is 120 bytes(including the database name, dot separator,
and the collection name).

Example:
db.books.insertOne({ title: "Learn MongoDB", author: "Jane Doe", year: 2023 })

Creating collection
After creating database now we create a collection to store documents. The collection is created
using the following syntax:
db.collection_name.insertOne({..})

 Database in MongoDB
 A Database in MongoDB is a container for data that holds multiple collections. MongoDB allows
the creation of multiple databases on a single server, enabling efficient data organization and
management for various applications. It’s the highest level of structure within
the MongoDB system.
 1. Multiple Databases: MongoDB allows you to create multiple databases on a single server. Each
database is logically isolated from others.
 2. Default Databases: When you start MongoDB, three default databases are
created: admin, config, and local. These are used for internal purposes.
 3. Database Creation: Databases are created when you insert data into them. You can create or
switch to a database using the following command:
 use <database_name>
 This command actually switches you to the new database if the given name does not exist and if
the given name exists, then it will switch you to the existing database. Now at this stage, if you
use the show command to see the database list where you will find that your new database is not
present in that database list because, in MongoDB, the database is actually created when we start
entering data in that database.
 4. View Database: To see how many databases are present in your MongoDB server, write the
following statement in the mongo shell:
 show dbs
Naming Restriction for Database:
Before creating a database we should first learn about the naming restrictions for databases:
 Database names must be case-insensitive.
 The names cannot contain special characters such as /, ., $, *, |, etc.
 MongoDB database names cannot contain null characters(in windows, Unix, and Linux systems).
 MongoDB database names cannot be empty and must contain less than 64 characters.

Q.2 Write basic MongoDB queries for CRUD operations using Node.js.

Basic MongoDB CRUD (Create, Read, Update, Delete) operations using Node.js with the official mongodb
driver are demonstrated below. These examples assume a connection to a MongoDB instance has already
been established.
1. Create (Insert):

const { MongoClient } = require('mongodb');

async function insertDocument(client, document) {


const db = client.db('yourDatabaseName');
const collection = db.collection('yourCollectionName');
const result = await collection.insertOne(document);
console.log(`Document inserted with _id: ${result.insertedId}`);
}

2. Read (Find):

const { MongoClient } = require('mongodb');

async function findDocuments(client, query = {}) {


const db = client.db('yourDatabaseName');
const collection = db.collection('yourCollectionName');
const cursor = collection.find(query);
const documents = await cursor.toArray();
console.log('Found documents:', documents);
return documents;
}

3. Update:
const { MongoClient } = require('mongodb');

async function updateDocument(client, filter, update) {


const db = client.db('yourDatabaseName');
const collection = db.collection('yourCollectionName');
const result = await collection.updateOne(filter, { $set: update });
console.log(`${result.matchedCount} document(s) matched,
${result.modifiedCount} document(s) modified.`);
}

4. Delete:

const { MongoClient } = require('mongodb');

async function deleteDocument(client, filter) {


const db = client.db('yourDatabaseName');
const collection = db.collection('yourCollectionName');
const result = await collection.deleteOne(filter);
console.log(`${result.deletedCount} document(s) deleted.`);
}

Q.3 How is data modeling in MongoDB? Demonstrate with a product schema

Data modeling in MongoDB involves designing the structure of your documents and collections to
efficiently store and retrieve data. Unlike relational databases, MongoDB offers a flexible schema, allowing
documents within a collection to have varying structures. This flexibility requires careful consideration of
how data will be accessed and updated to optimize performance.
{
"_id": ObjectId("60d5f9..."),
"name": "Wireless Headphones",
"description": "Bluetooth over-ear headphones with noise cancellation",
"price": 299.99,
"inStock": true,
"tags": ["audio", "wireless", "bluetooth"],
"category": {
"id": "123",
"name": "Electronics"
},
"reviews": [
{
"user": "John",
"rating": 5,
"comment": "Great sound quality!"
},
{
"user": "Emma",
"rating": 4,
"comment": "Very comfortable to wear"
}
],
"createdAt": "2025-06-21T10:00:00Z"
}
Q.4 Discuss the role of Mongoose in MERN applications.

Mongoose is an elegant Object Data Modeling (ODM) library for MongoDB and Node.js, serving as a
crucial component in the MERN (MongoDB, Express.js, React, Node.js) stack. It provides a straight-
forward, schema-based solution to model your application data while offering features like validation, query
building, and business logic hooks.

Use Mongoose in MERN


1. Schema Enforcement: While MongoDB is schema-less, Mongoose allows you to define schemas for
your data, bringing structure to your documents
2. Validation: Built-in and custom validation for data before it hits the database
3. Middleware: Pre and post hooks for operations
4. Population: Easy handling of relationships between data
5. Business Logic: Instance methods and static methods to encapsulate model-related logic

First, install Mongoose in your Node.js backend :


npm install mongoose

Use the Model in Express Routes

const express = require('express');


const router = express.Router();
const Product = require('../models/Product');
router.post('/', async (req, res) => {
try {
const product = new Product(req.body);
const saved = await product.save();
res.status(201).json(saved);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
router.get('/', async (req, res) => {
const products = await Product.find();
res.json(products);
});

module.exports = router;
Defining a Schema and Model

const mongoose = require('mongoose');

const productSchema = new mongoose.Schema({


name: { type: String, required: true },
price: Number,
inStock: Boolean
});
const Product = mongoose.model('Product', productSchema);
module.exports = Product;
Connect to MongoDB

const express = require('express');


const mongoose = require('mongoose');
const productRoutes = require('./routes/productRoutes');

const app = express();


app.use(express.json());
app.use('/products', productRoutes);

mongoose.connect('mongodb://localhost:27017/mernshop')
.then(() => {
console.log('MongoDB connected via Mongoose');
app.listen(5000, () => console.log(' Server running on port 5000'));
})
.catch(err => console.error(' Connection error:', err));

Q.5 What is Webpack? Explain its role in bundling front-end assets.

Webpack is a static module bundler for JavaScript applications that helps manage and optimize front-end
assets. It takes your application's code, including JavaScript, CSS, images, and other assets, and bundles
them into optimized static files that can be easily loaded by web browsers. Webpack helps developers
organize code, handle dependencies, and improve performance by optimizing assets for faster loading.

Here's a more detailed explanation:

 Modular JavaScript:
Webpack treats all files as modules and helps manage dependencies between them, allowing
developers to write modular and maintainable code.

 Asset Transformation:
Webpack uses loaders to process various asset types (like CSS, images, fonts) and transform
them into modules that can be included in the final bundles.
 Dependency Graph:
Webpack builds a dependency graph to understand how different modules are related and
uses this graph to create optimized bundles.

 Bundling:
Webpack combines these modules and assets into a smaller number of bundles, reducing the
number of HTTP requests needed to load a web page and improving performance.

 Optimization:
Webpack offers various optimizations like code splitting, tree shaking, minification, and
caching to further improve performance and reduce bundle sizes.

Q.6 Compare front-end and back-end modules with examples

Frontend Backend

Refers to the client-side of the web


Refers to the server side of the web application.
application.

Involves technologies like HTML, CSS, Involves technologies like PHP, Python, Node.js,
JavaScript, and frameworks Ruby, and databases like MySQL, MongoDB, and
like React, Vue.js, and Angular. PostgreSQL.

The average salary of the Frontend Developer The average salary of the Backend Developer is
is $80,796 $90,652

Work closely with designers, UX/UI Work closely with front-end developers, system
developers, and back-end developers administrators, and database administrators

Deals with UI design, user interaction, and Deals with data processing, server communication,
performance on the client side. and storing/retrieving data from databases.

Frontend developer uses tools to create an The back-end developer builds the server, database,
Frontend Backend

interface and focus on the user experience. and application logic, focusing on the application's
performance.

Ensures that the website processes data,


Ensures that the website is visually
communicates with the database, and handles server
appealing, responsive, and interactive.
requests.

Front-end developers are in high demand due Back-end developers are also in high demand,
to the increasing emphasis on user experience especially with the growth of data-driven
(UX) and interface design. applications, cloud services, and APIs.

Q.7 Explain Hot Module Replacement (HMR) and its use in development

Hot Module Replacement (HMR) is a development tool that allows you to update parts of your running
application without requiring a full page reload. It provides a faster feedback loop during development by
only updating the changed modules while preserving the application's state. This is especially useful for
large, complex applications where a full reload can be time-consuming and disruptive.
Here's a more detailed explanation:

How it works:
 HMR works by identifying the specific modules that have been changed and replacing them in the
running application.
 Instead of a complete page refresh, HMR applies these changes dynamically, preserving the
application's current state (e.g., form data, scroll position).
 This process is facilitated by module bundlers like Webpack and Vite, which provide the necessary
infrastructure and APIs for HMR to function.

Benefits of HMR:
 Faster development cycles:
By eliminating the need for full page reloads, HMR significantly speeds up the development process.
 State preservation:
HMR ensures that the application's state is not lost during updates, allowing developers to see
changes in context without having to re-navigate or re-enter data.
 Improved developer experience:
The ability to see changes instantly and without disruption makes development more intuitive
and engaging.

 Reduced development time:


HMR can save significant development time, especially in large projects where full reloads
can be time-consuming.

Use cases:

 Front-end development:
HMR is widely used in front-end development with frameworks like React, Vue, and
Angular, as well as with module bundlers like Webpack and Vite.

 Large and complex applications:


HMR is particularly beneficial for projects with intricate dependency trees and complex
application states.

 Debugging and testing:


HMR can be used to quickly test and debug changes in a live environment, making it easier
to identify and fix issues.

Key Benefits of HMR

 Preserves application state: Form inputs, scroll position, and UI state remain intact

 Faster development cycles: No need to manually refresh after every change

 CSS updates instantly: Style changes appear immediately without reload

 Partial updates: Only modified components are reloaded

Q.8 Write a build configuration using Webpack with DefinePlugin and production
optimization.
const path = require('path');
const webpack = require('webpack');
const TerserPlugin = require('terser-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');

module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
filename: '[name].[contenthash].js',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production'),
'__PRODUCTION__': JSON.stringify(true),
'__API_URL__': JSON.stringify('https://api.yourdomain.com/production'),
}),
],
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
terserOptions: {
compress: {
drop_console: true,
},
},
}),
new CssMinimizerPlugin(),
],
splitChunks: {
chunks: 'all',
},
runtimeChunk: 'single',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
},
},
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
],
},
};

You might also like