0% found this document useful (0 votes)
10 views49 pages

Module - 1: 1. Explain Different Data Types in Javascript With Suitable Examples

The document covers various aspects of full stack development with a focus on JavaScript, including data types, variable declarations, functions, and DOM manipulation. It explains primitive and non-primitive data types, the differences between var, let, and const, and provides examples of string operations and event handling. Additionally, it discusses event delegation versus direct event binding and how to dynamically update HTML attributes using JavaScript.
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)
10 views49 pages

Module - 1: 1. Explain Different Data Types in Javascript With Suitable Examples

The document covers various aspects of full stack development with a focus on JavaScript, including data types, variable declarations, functions, and DOM manipulation. It explains primitive and non-primitive data types, the differences between var, let, and const, and provides examples of string operations and event handling. Additionally, it discusses event delegation versus direct event binding and how to dynamically update HTML attributes using JavaScript.
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/ 49

FULL STACK DEVELOPMENT BIS601

Module – 1
1. Explain different data types in JavaScript with suitable examples.
 Data types define the kind of values a variable can hold in JavaScript. JavaScript is
dynamically typed, meaning we don’t need to declare the data type explicitly; it is
assigned automatically based on the value.
JavaScript has two main types of data:
1. Primitive Data Types (Stores a single value)
2. Non-Primitive (Reference) Data Types (Stores collections of values)
 Primitive Data Types
These are immutable (cannot be changed) and store single values.
1. String
Used to store text, enclosed in single ('), double ("), or backticks ( `).
let name = "Deepika";
let greeting = 'Hello';
let message = `Welcome to JavaScript!`;
console.log(name, greeting, message);
2️. Number
Holds both integer and floating-point values.
let age = 25;
let price = 99.99;
console.log(age, price);
3️. Boolean
Represents true or false values.
let isStudent = true;
let hasPassed = false;
console.log(isStudent, hasPassed);
4️. BigInt
Used for large numbers beyond Number. MAX_SAFE_INTEGER.
let bigNum = 9007199254740991n;
console.log(bigNum);
5️. Undefined
A variable is undefined when it is declared but not assigned a value.
let value;
FULL STACK DEVELOPMENT BIS601

console.log(value);
6️. Null
Represents an intentional absence of value.
let data = null;
console.log(data);
7️. Symbol
Used to create unique identifiers.
let id1 = Symbol('id');
let id2 = Symbol('id');
console.log(id1 === id2);
 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());

2️. Write a JavaScript program using loops and conditions to print prime
numbers between 1 to 100.
 for (let num = 2 ; num <= 100 ; num++) {
FULL STACK DEVELOPMENT BIS601

let isPrime = true;


for (let i=2 ; i<=Math.sqrt(num); i++) {
if (num % i=== 0) {
isPrime = false;
break;
}
}
if (isPrime) {
console.log(num);
}
}
 We loop from 2 to 100 (since 1 is not a prime number).
 For each number, we check if it’s divisible by any number from 2 to _/num
(Optimization to reduce checks).
 If a factor is found, we mark isPrime = false.
 If no factors are found, we print the number --- it’s a prime.

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


 In JavaScript, var, let, and const are used to declare variables, but they have important
differences in scope, hoisting, and mutability.
1. var
 Scope: Function-scoped
 Hoisting: Variables are hoisted and initialized as undefined
 Re-declaration: Allowed within the same scope
Example:
function testVar() {
if (true) {
var x = 10;
}
console.log(x);
}
testVar();
FULL STACK DEVELOPMENT BIS601

2️. let
 Scope: Block-scoped
 Hoisting: Variables are hoisted but not initialized (temporal dead zone)
 Re-declaration: Not allowed in the same scope
Example:
function testLet() {
if (true) {
let y = 20;
console.log(y);
}
console.log(y);
}
testLet();
3️. const
 Scope: Block-scoped
 Hoisting: Same as let
 Re-declaration: Not allowed in the same scope
 Assignment: Must be initialized at declaration; cannot be reassigned
Example:
const z = 30;
console.log(z);
Note: Objects and arrays declared with const can still be mutated.
const obj = { name: "Alice" };
obj.name = "Bob";
console.log(obj.name);

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


 Here's a simple JavaScript function to sort an array of strings alphabetically:
function sortStringsAlphabetically(arr) {
return arr.sort();
}
// Example usage
const fruits = ["Banana", "Apple", "Mango", "Cherry"];
FULL STACK DEVELOPMENT BIS601

const sortedFruits = sortStringsAlphabetically(fruits);


console.log(sortedFruits);
Notes:
 The .sort() method sorts strings alphabetically by default (based on Unicode code
points).
 It modifies the original array, so if you want to keep the original array unchanged, you
can clone it first:
function sortStringsAlphabetically(arr) {
return [...arr].sort();
}

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


object methods.
 In JavaScript, objects are collections of key-value pairs used to store related data and
functionality. Keys are strings (also called properties), and the values can be of any type
(strings, numbers, arrays, functions, etc.).
JavaScript objects are similar to dictionaries in Python or maps in other languages.
Creating a Custom Object
Let's create a custom object to represent a Car, with properties and methods.
const car = {
brand: "Toyota",
model: "Corolla",
year: 2020,
mileage: 50000,
displayInfo: function () {
console.log(`Car: ${this.brand} ${this.model} (${this.year})`);
},
drive: function (distance) {
this.mileage += distance;
console.log(`Driven ${distance} km. New mileage is ${this.mileage} km.`);
}
};
car.displayInfo();
FULL STACK DEVELOPMENT BIS601

car.drive(150);
Explanation
 Properties: brand, model, year, and mileage store the state of the object.
 Methods:
o displayInfo(): Logs the car's basic info.
o drive(distance): Adds to the mileage and logs the new mileage.

6️.Write a program to demonstrate string operations like slicing,


concatenation, and replacement.
 Here's a simple JavaScript program that demonstrates string slicing, concatenation, and
replacement:
// Original string
let originalString = "Hello, JavaScript World!";
// 1. Slicing (extract a substring)
let slicedString = originalString.slice(7, 17); // From index 7 to 16
console.log("Sliced String:", slicedString); // Output: "JavaScript"
// 2. Concatenation (combine strings)
let greeting = "Hello";
let language = "JavaScript";
let combined = greeting + ", " + language + "!";
console.log("Concatenated String:", combined); // Output: "Hello, JavaScript!"
// 3. Replacement (replace part of the string)
let replacedString = originalString.replace("JavaScript", "TypeScript");
console.log("Replaced String:", replacedString); // Output: "Hello, TypeScript World!"
🔍 Breakdown:
 .slice(start, end): Extracts a substring from start index to just before end.
 +: Used to concatenate (combine) strings.

 .replace(oldValue, newValue): Replaces the first match of oldValue with newValue.


FULL STACK DEVELOPMENT BIS601

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


JavaScript.
 1. Comments
Role:
 Explain code and improve readability.
 Temporarily disable code during debugging.
 Ignored by the JavaScript engine.
Syntax:
// Single-line comment
/*
Multi-line
comment
*/
Example:
// This is a single-line comment
let x = 10;
/*
This is a multi-line comment
describing the next function
*/
function greet() {
console.log("Hello!");
}
2️. Statements
Role:
 Perform actions (e.g., declarations, conditionals, loops).
 JavaScript code is made up of statements.
 Typically end with a semicolon (;), though optional in many cases.
Examples:
let a = 5;
if (a > 0) {
console.log("Yes");
}
FULL STACK DEVELOPMENT BIS601

for (let i = 0; i < 3; i++) {


console.log(i);
}
3️. Expressions
Role:
 Produce a value.
 Can be assigned to variables, used in conditions, returned from functions.
Examples:
2+3
"Hello" + " World"
let b = a * 2;
In this line:
let sum = 5 + 10;
 5 + 10 is an expression (produces a value).
 let sum = 5 + 10; is a statement (performs an action).

8.Design a calculator program that uses function to perform basic operations


(+,-,×,÷).
 JavaScript Calculator with Functions
// Define basic operation functions
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function multiply(a, b) {
return a * b;
}
function divide(a, b) {
if (b === 0) {
return "Error: Division by zero";
}
FULL STACK DEVELOPMENT BIS601

return a / b;
}
// Calculator function
function calculator(a, b, operator) {
switch (operator) {
case "+":
return add(a, b);
case "-":
return subtract(a, b);
case "*":
return multiply(a, b);
case "/":
return divide(a, b);
default:
return "Error: Invalid operator";
}
}
// Example usage
console.log("10 + 5 =", calculator(10, 5, "+")); // 15
console.log("10 - 5 =", calculator(10, 5, "-")); // 5
console.log("10 × 5 =", calculator(10, 5, "*")); // 50
console.log("10 ÷ 5 =", calculator(10, 5, "/")); // 2
console.log("10 ÷ 0 =", calculator(10, 0, "/")); // Error
✅ Output:
10 + 5 = 15
10 - 5 = 5
10 × 5 = 50
10 ÷ 5 = 2
10 ÷ 0 = Error: Division by zero
FULL STACK DEVELOPMENT BIS601

Module - 2️
1. Explain the Document Object Model (DOM) and its tree structure.
 What is the Document Object Model (DOM)?
The DOM (Document Object Model) is a programming interface provided by browsers that
allows JavaScript (or other languages) to access and manipulate HTML and XML documents.
 DOM is a neither part of html, nor part of javascript.
 It is a separate set of rules.
 It is implemented by all major browser make use and covers to primary area.
1. Make a model of the html page.
2. Accessing and changing the html page.
Think of the DOM as a tree-like structure where:
 Each HTML element becomes a node.
 The entire document is a tree of nodes that can be traversed, updated, deleted, or created
dynamically.
🌳 DOM Tree Structure
Example HTML:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Hello, DOM!</h1>
<p>This is a paragraph.</p>
</body>
</html>
Corresponding DOM Tree:
Document

├── html
│ ├── head
│ │ └── title
│ │ └── "My Page"
FULL STACK DEVELOPMENT BIS601

│ └── body
│ ├── h1
│ │ └── "Hello, DOM!"
│ └── p
│ └── "This is a paragraph."

2️.Write JavaScript code to select an element and change its content


dynamically.
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Content Change</title>
</head>
<body>
<h1 id="heading">Welcome!</h1>
<button onclick="changeContent()">Click to Change Heading</button>
<script>
// Function to change content
function changeContent() {
const heading = document.getElementById("heading"); // Select element by ID
heading.textContent = "Hello, JavaScript World!"; // Change content
}
</script>
</body>
</html>
Explanation:
 document.getElementById("heading"): Selects the <h1> element with the ID
heading.
 textContent: Replaces the current content inside the heading.
 onclick event: Calls the changeContent() function when the button is clicked.
FULL STACK DEVELOPMENT BIS601

3️. What are event listeners? Create an example using addEventListener() for
a button click.
 What Are Event Listeners in JavaScript?
Event listeners are functions that wait for a specific event (like a click, key press, or mouse
hover) to occur on a particular element, and then run code in response.
Instead of using inline onclick, you can attach events using the more flexible and powerful
addEventListener() method.
Syntax:
element.addEventListener(event, function);
 element: The HTML element to listen on.
 event: A string like "click", "mouseover", "keydown", etc.
 function: The callback function to run when the event occurs.
Example: addEventListener() for Button Click
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Event Listener Example</title>
</head>
<body>
<button id="myButton">Click Me</button>
<p id="message"></p>
<script>
// Select the button element
const button = document.getElementById("myButton");
// Add an event listener for the click event
button.addEventListener("click", function() {
document.getElementById("message").textContent = "Button was clicked!";
});
</script>
</body>
</html>
FULL STACK DEVELOPMENT BIS601

What Happens:
 The user clicks the "Click Me" button.
 The event listener detects the click.
 The callback function updates the text in the <p> element to say:
"Button was clicked!"
Why Use addEventListener()?
 Supports multiple listeners for the same event.
 Clean separation of JavaScript and HTML.
 Works with removeEventListener() for better control.

4️.Describe the differences between event delegation and direct event binding.
 1.Direct Event Binding
What is it?
You attach an event listener directly to a specific DOM element.
Example:
document.getElementById("btn").addEventListener("click", function() {
alert("Button clicked!");
});
✅Pros:
 Simple and clear for small sets of elements.
 Easy to implement for static elements.
❌ Cons:
 Doesn't work for dynamically added elements unless re-bound.
 Can lead to performance issues if many elements need listeners.
2️. Event Delegation
What is it?
You attach a single event listener to a parent element, and use event bubbling to handle events
on its children.
Example:
document.getElementById("parent").addEventListener("click", function(event) {
if (event.target.tagName === "BUTTON") {
alert("A button inside the parent was clicked!");
}
FULL STACK DEVELOPMENT BIS601

});
✅ Pros:
 Efficient: only one listener for many child elements.
 Works for dynamically added elements.
 Better performance in large or frequently updated UIs.
❌ Cons:
 Slightly more complex to implement (need to check event.target).
 Can lead to unexpected behavior if not scoped properly.
When to Use What?
 Use Direct Binding when you have a few static elements.
 Use Event Delegation when:
o You're dealing with dynamically added elements (e.g., from user input or
AJAX).
o You want optimal performance with lots of interactive elements.

5️. Explain how to update element attributes using JavaScript.


 How to Update Element Attributes Using JavaScript
In JavaScript, you can update, add, or remove attributes of HTML elements dynamically
using a few built-in methods.
Common Methods to Update Attributes:
1. setAttribute(name, value)
Sets or updates the value of the specified attribute.
document.getElementById("myImage").setAttribute("src", "new-image.jpg");
2️. getAttribute(name)
Retrieves the current value of an attribute.
let altText = document.getElementById("myImage").getAttribute("alt");
3️. Direct Property Access
Some attributes (like id, href, value, checked, etc.) can be updated directly as properties.
document.getElementById("myLink").href = "https://www.example.com";
4️. removeAttribute(name)
Removes an attribute from the element.
document.getElementById("myInput").removeAttribute("disabled");
FULL STACK DEVELOPMENT BIS601

Example: Updating Attributes


<!DOCTYPE html>
<html>
<head>
<title>Update Attributes Example</title>
</head>
<body>
<img id="myImage" src="old.jpg" alt="Old Image" width="200">
<br>
<button onclick="updateImage()">Change Image</button>
<script>
function updateImage() {
const img = document.getElementById("myImage");
img.setAttribute("src", "new.jpg"); // Change image source
img.setAttribute("alt", "New Image"); // Update alt text
img.width = 300; // Directly update width
}
</script>
</body>
</html>

6️. Discuss various types of browser events with examples


 Certainly! In JavaScript, browser events are actions or occurrences that happen in the
browser, often as a result of user interaction or system behavior. JavaScript can listen for
and respond to these events using event listeners.
Common Types of Browser Events (with Examples)
1. Mouse Events
Triggered by mouse actions like clicks, movements, etc.
Event Type Description Example
click When an element is clicked button.addEventListener("click", ...)
dblclick When an element is double-clicked
mouseover Mouse pointer moves over an element
FULL STACK DEVELOPMENT BIS601

Event Type Description Example


mouseout Mouse pointer leaves an element
mousedown Mouse button is pressed
mouseup Mouse button is released
javascript code
document.getElementById("myBtn").addEventListener("click", function() {
alert("Button clicked!");
});
2️. Keyboard Events
Triggered by keyboard input.
Event Type Description
keydown A key is pressed down
keyup A key is released
keypress A key is pressed and held (deprecated in modern browsers)
javascript code
document.addEventListener("keydown", function(event) {
console.log("Key pressed:", event.key);
});
3️. Form Events
Related to form inputs and submission.
Event Type Description
submit When a form is submitted
change When an input field value changes
focus When an element gains focus
blur When an element loses focus
input Fires whenever the input value changes
Javascript code
document.getElementById("myForm").addEventListener("submit", function(e) {
e.preventDefault(); // Prevents form from submitting
alert("Form submitted!");
});
FULL STACK DEVELOPMENT BIS601

4️. Window Events


These relate to the browser window itself.
Event Type Description
load When the page is fully loaded
resize When the window is resized
scroll When the page is scrolled
unload When the page is exited (deprecated)
javascript code
window.addEventListener("load", function() {
console.log("Page fully loaded.");
});
5️. Clipboard Events
These respond to cut, copy, and paste actions.
Event Type Description
copy User copies content
cut User cuts content
paste User pastes content
Javascript code
document.addEventListener("paste", function() {
alert("You pasted something!");
});

7️. Implement a script that changes the background color of a page on a


mouseover event.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Mouseover Background Color Change</title>
<style>
body {
transition: background-color 0.3s ease;
FULL STACK DEVELOPMENT BIS601

margin: 0;
height: 100vh;
}
</style>
</head>
<body>
<script>
// Change background color on mouseover
document.body.addEventListener('mouseover', function () {
document.body.style.backgroundColor = getRandomColor();
});
// Optional: Reset background color on mouseout
document.body.addEventListener('mouseout', function () {
document.body.style.backgroundColor = '';
});
// Helper function to generate a random color
function getRandomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
</script>
</body>
</html>
How It Works:
 On mouseover, the background color changes to a random color.
 On mouseout, the background resets (you can remove this part if you want the color to
stay).
FULL STACK DEVELOPMENT BIS601

8.Write code that listens for keyboard input and logs the key pressed.
from pynput import keyboard
def on_press(key):
try:
print(f'Key {key.char} pressed')
except AttributeError:
print(f'Special key {key} pressed')
def on_release(key):
if key == keyboard.Key.esc:
# Stop listener on Escape key
print("Exiting...")
return False
# Set up the listener
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
FULL STACK DEVELOPMENT BIS601

Module – 3️
1. Describe the importance of form validation and write a simple form with
client-side validation.
 Importance of Form Validation
Form validation ensures that the data entered by users into a form meets the expected format
and rules before it is submitted to the server. It plays a crucial role in both user experience and
data integrity. Here's why it's important:
1. Improves Data Accuracy: Prevents users from submitting incorrect or incomplete
data.
2. Enhances Security: Helps prevent malicious data (e.g., SQL injections, XSS).
3. Reduces Server Load: Filters out invalid input on the client side before it reaches the
server.
4. Improves User Feedback: Provides immediate guidance if the user makes a mistake.
5. Prevents Errors: Reduces backend errors caused by malformed or unexpected input.
Simple HTML Form with Client-Side Validation
Here's a basic example of a registration form with client-side validation using HTML5 and
JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Registration Form</title>
<style>
label, input {
display: block;
margin: 10px 0;
}
.error {
color: red;
font-size: 0.9em;
}
</style>
</head>
FULL STACK DEVELOPMENT BIS601

<body>
<h2>Register</h2>
<form id="registrationForm">
<label>
Username:
<input type="text" id="username" name="username" required minlength="3">
</label>
<label>
Email:
<input type="email" id="email" name="email" required>
</label>
<label>
Password:
<input type="password" id="password" name="password" required minlength="6">
</label>
<button type="submit">Submit</button>
<p class="error" id="errorMessage"></p>
</form>
<script>
const form = document.getElementById('registrationForm');
const errorMessage = document.getElementById('errorMessage');
form.addEventListener('submit', function(event) {
errorMessage.textContent = ''; // Reset error message
const username = document.getElementById('username').value.trim();
const email = document.getElementById('email').value.trim();
const password = document.getElementById('password').value;
if (username.length < 3) {
errorMessage.textContent = "Username must be at least 3 characters.";
event.preventDefault();
return;
}
if (!email.includes('@')) {
errorMessage.textContent = "Please enter a valid email address.";
event.preventDefault();
FULL STACK DEVELOPMENT BIS601

return;
}
if (password.length < 6) {
errorMessage.textContent = "Password must be at least 6 characters.";
event.preventDefault();
return;
}
});
</script>
</body>
</html>
Key Features:
 Uses HTML5️ validation attributes (required, minlength, type="email").
 Adds JavaScript validation for custom messages and further checks.
 Provides real-time feedback on incorrect entries.

2️. Explain the MERN stack architecture with a brief role of each
component.
 The MERN stack is a popular set of technologies used to build full-stack web applications
using JavaScript for both client and server sides. MERN is an acronym for:
1. MongoDB
2. Express.js
3. React.js
4. Node.js
MERN Stack Architecture & Component Roles:
1. MongoDB (Database Layer)
 Role: NoSQL database used to store application data in a flexible, JSON-like format
(BSON).
 Use: It stores user information, app data, and supports scalable, high-performance
queries.
 Example: User profiles, product data, or blog posts are saved here.
FULL STACK DEVELOPMENT BIS601

2️. Express.js (Backend Framework)


 Role: Lightweight web framework for Node.js to handle HTTP requests and build
RESTful APIs.
 Use: Acts as the middleware that routes and processes incoming requests.
 Example: When a user logs in, Express handles the login request and interacts with
MongoDB to validate credentials.
3️. React.js (Frontend Framework)
 Role: JavaScript library for building user interfaces, especially SPAs (Single Page
Applications).
 Use: Renders components dynamically, manages UI state, and interacts with backend
APIs.
 Example: A React form sends login data to the Express backend via an API call.
4️. Node.js (Runtime Environment)
 Role: JavaScript runtime that allows server-side scripting.
 Use: Runs the backend server and serves the Express application.
 Example: Starts the server, listens on ports, and handles backend logic.

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


import React from 'react';
const TaskList = ({ tasks }) => {
return (
<div>
<h2>Tasks</h2>
{tasks && tasks.length > 0 ? (
<ul>
{tasks.map((task, index) => (
<li key={index}>
<span>{task.name}</span> - <em>{task.completed ? 'Completed' :
'Incomplete'}</em>
</li>
))}
</ul>
):(
FULL STACK DEVELOPMENT BIS601

<p>No tasks to display.</p>


)}
</div>
);
};
export default TaskList;

4️. Differentiate between class-based and functional components in React.


 Class-Based vs Functional Components
Feature Class-Based Component Functional Component
Uses plain JavaScript functions
Syntax Uses ES6 classes
or arrow functions

State Handling Uses this.state and this.setState() Uses useState Hook

Lifecycle Has built-in lifecycle methods (e.g.,


Uses Hooks like useEffect
Methods componentDidMount)

Code Length Generally longer and more verbose More concise and readable

Requires use of this to access


this Keyword No this keyword required
props/state

Hooks Support ❌ Not supported ✅ Fully supports Hooks

Recommended
Legacy codebases Preferred in modern React
Use

5️. Create a simple issue tracker using component composition and static
data.
 Components Overview:
1. App – Main container
2. IssueList – Lists all issues
3. IssueItem – Displays a single issue
Static Issue Data
// issues.js (or inside App.js for simplicity)
export const issues = [
{
FULL STACK DEVELOPMENT BIS601

id: 1,
title: 'Bug in login form',
status: 'Open',
description: 'Login button doesn’t respond on click.'
},
{
id: 2,
title: 'UI misalignment on dashboard',
status: 'In Progress',
description: 'Sidebar overlaps the content on smaller screens.'
},
{
id: 3,
title: 'Broken link in footer',
status: 'Closed',
description: 'The "Contact Us" link returns 404.'
}
];
App.js
import React from 'react';
import IssueList from './IssueList';
import { issues } from './issues';
const App = () => {
return (
<div style={{ padding: '20px' }}>
<h1>Simple Issue Tracker</h1>
<IssueList issues={issues} />
</div>
);
};
export default App;
IssueList.js
import React from 'react';
import IssueItem from './IssueItem';
FULL STACK DEVELOPMENT BIS601

const IssueList = ({ issues }) => {


return (
<div>
{issues.map((issue) => (
<IssueItem key={issue.id} issue={issue} />
))}
</div>
);
};
export default IssueList;
IssueItem.js
import React from 'react';
const IssueItem = ({ issue }) => {
const { title, status, description } = issue;
return (
<div style={{
border: '1px solid #ccc',
padding: '10px',
marginBottom: '10px',
borderRadius: '5px'
}}>
<h3>{title}</h3>
<p><strong>Status:</strong> {status}</p>
<p>{description}</p>
</div>
);
};
export default IssueItem;

6️. What are children props? Demonstrate passing data using children.
 What Are children Props?
The children prop is automatically provided by React. It represents everything inside a
component's opening and closing tag.
FULL STACK DEVELOPMENT BIS601

Use Case Example: Passing Data with children


1. Parent Component (using children):
function App() {
return (
<Card>
<h2>Hello from inside the Card!</h2>
<p>This is some extra content passed as children.</p>
</Card>
);
}
2️. Child Component (accepts and uses children):
function Card({ children }) {
return (
<div style={{ border: "2px solid black", padding: "10px" }}>
{children}
</div>
);
}
Why Use children?
 Allows composition: wrap components or HTML inside others.
 Improves flexibility: don't hard-code everything into components.
 Useful for layouts, modals, cards, containers, etc.

7️. Design a React component that conditionally renders content based on a boolean
prop.
 Component: StatusMessage
import React from 'react';
function StatusMessage({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? (
<h2>Welcome back, user! 🎉</h2>
):(
FULL STACK DEVELOPMENT BIS601

<h2>Please log in to continue. 🔒</h2>


)}
</div>
);
}
export default StatusMessage;
Usage Example
import React from 'react';
import ReactDOM from 'react-dom';
import StatusMessage from './StatusMessage';
function App() {
const userLoggedIn = true; // Change to false to test
return (
<div>
<StatusMessage isLoggedIn={userLoggedIn} />
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));

8. Write a Hello World MERN setup explanation with a minimal code base.
 Here's a minimal "Hello World" MERN stack setup explanation. MERN stands for:
 MongoDB – NoSQL database
 Express.js – Web framework for Node.js
 React – Frontend library
 Node.js – JavaScript runtime for backend
We'll set up a project where the backend serves an API and the frontend displays "Hello World"
fetched from that API.
1. Project Structure
mern-hello-world/
├── backend/
│ ├── server.js
├── frontend/
FULL STACK DEVELOPMENT BIS601

│ ├── public/
│ ├── src/
│ │ ├── App.js
│ │ └── index.js
│ └── package.json
├── package.json
2️. Setup Instructions
Step 1: Initialize Root
mkdir mern-hello-world && cd mern-hello-world
npm init -y # root package.json (optional)
Step 2️: Backend Setup
mkdir backend && cd backend
npm init -y
npm install express cors
backend/server.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 World from Backend!' });
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Run the backend:
bash
Copy code
node server.js
Step 3️: Frontend Setup (with Create React App)
cd ..
npx create-react-app frontend
cd frontend
FULL STACK DEVELOPMENT BIS601

npm install
frontend/src/App.js
import React, { useEffect, useState } from 'react';
function App() {
const [message, setMessage] = useState('Loading...');
useEffect(() => {
fetch('http://localhost:5000/api/hello')
.then((res) => res.json())
.then((data) => setMessage(data.message))
.catch((err) => setMessage('Error fetching message'));
}, []);
return <h1>{message}</h1>;
}
export default App;
FULL STACK DEVELOPMENT BIS601

Module - 4️

1. Define React state and explain how to initialize and update it.
 What is React State?
React state is a built-in object that stores dynamic data for a component. It determines
how that component behaves and renders. When the state changes, React automatically
re-renders the component to reflect those changes in the UI.
Think of it as a component’s memory that updates the UI when something changes.
How to Initialize and Update State (with Examples)
React uses the useState hook (in functional components) to create and manage state.
1. Import useState
import { useState } from 'react';
2️. Initialize State
const [count, setCount] = useState(0);
 count: current state value
 setCount: function used to update the state
 0: initial state value
3️. Update State
Call the setter function with a new value:
setCount(count + 1);
React will re-render the component with the updated state.
Full Example
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // Initialization
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click Me</button>
</div>
);
}
export default Counter;
FULL STACK DEVELOPMENT BIS601

Every time the button is clicked:


 setCount updates the state
 React re-renders the component
 The updated count value is displayed

2️. Implement a React component using useState and useEffect for counter
behavior.
 Functional Counter Component
import React, { useState, useEffect } from 'react';
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log(`Count updated: ${count}`);
}, [count]);
return (
<div style={{ textAlign: 'center', marginTop: '2rem' }}>
<h2>Counter</h2>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button
onClick={() => setCount((prev) => (prev > 0 ? prev - 1 : 0))}
style={{ marginLeft: '1rem' }}
>
Decrement
</button>
</div>
);
}
export default Counter;
Breakdown
useState:
 Initializes the counter to 0.
 Updates the counter via setCount().
FULL STACK DEVELOPMENT BIS601

useEffect:
 Runs every time count changes.
 In this case, logs to the console. Could be used for syncing data, animations, etc.

3️. Explain the concept of "lifting state up" in React with an example.
 What is "Lifting State Up" in React?
Lifting state up means moving state from a child component to a common parent, so
that multiple child components can share and synchronize that state.
When two or more components need access to the same state, that state should be "lifted"
to their nearest common ancestor.
Why Lift State?
 To avoid duplication of state.
 To enable components to communicate via shared state in a parent.
 To maintain a single source of truth.
Example: Lifting State Up
Goal: Two child components need to sync a value (e.g. input and label).
Structure:
App (holds shared state)
├── InputComponent (updates state)
└── DisplayComponent (reads state)
Code
import React, { useState } from 'react';
import InputComponent from './InputComponent';
import DisplayComponent from './DisplayComponent';
function App() {
const [text, setText] = useState('');
return (
<div style={{ textAlign: 'center', marginTop: '2rem' }}>
<h2>Lifting State Up Example</h2>
<InputComponent text={text} setText={setText} />
<DisplayComponent text={text} />
</div>
);
FULL STACK DEVELOPMENT BIS601

}
export default App;
// InputComponent.js
import React from 'react';
function InputComponent({ text, setText }) {
return (
<input
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Type something..."
/>
);
}
export default InputComponent;
// DisplayComponent.js
import React from 'react';
function DisplayComponent({ text }) {
return <p>You typed: {text}</p>;
}
export default DisplayComponent;

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


 Real-World Analogy: A Smart Thermostat in a House
Props = What the owner gives the thermostat
State = What the thermostat knows and manages on its own
Props = External Instructions
Imagine a homeowner installs a smart thermostat and sets the desired temperature to
7️2️°F. This desired temperature is a prop — it's passed into the thermostat from the outside
(the homeowner).
Props are read-only, controlled by parent (like the homeowner giving settings to the
device).
State = Internal Memory
Now, the thermostat has internal sensors that detect the current room temperature. It
may also track whether it's heating or cooling at the moment.
FULL STACK DEVELOPMENT BIS601

This dynamic, changing information is the state — it belongs inside the thermostat and
changes over time as the room warms up or cools down.
State is managed internally, mutable, and changes over time due to events or interactions.
React Comparison Summary
Feature Props State
Defined by Parent component Component itself
Can
No (read-only) Yes (mutable)
change?
Controlled
Parent Component internally
by
Use case Pass data to child Track internal component changes
Thermostat's target Thermostat’s current room temp
Analogy
temperature (set by user) (changes over time)

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


 What is a GraphQL Schema?
A GraphQL schema is the contract between the client and the server. It defines:
 Types of data (like User, Post, etc.)
 Relationships between types
 Operations that clients can perform:
o Queries: fetch data
o Mutations: modify data
o (Optionally) Subscriptions: real-time data
In short, the schema is the blueprint that tells the client what is available and how to ask
for it.
Simple Example: User Profile API
1. GraphQL Schema Definition
# Define a type
type User {
id: ID!
name: String!
email: String!
}
FULL STACK DEVELOPMENT BIS601

# Define a root query type


type Query {
getUser(id: ID!): User
}
# Define a mutation type
type Mutation {
createUser(name: String!, email: String!): User
}

6️. Write a sample Express.js REST API to create and fetch product data.
Create index.js
 // index.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const PORT = 3000;
app.use(bodyParser.json());
let products = [];
let idCounter = 1;
app.get('/api/products', (req, res) => {
res.json(products);
});
app.get('/api/products/:id', (req, res) => {
const product = products.find(p => p.id === parseInt(req.params.id));
if (!product) {
return res.status(404).json({ error: 'Product not found' });
}
res.json(product);
});
app.post('/api/products', (req, res) => {
const { name, price } = req.body;
if (!name || price === undefined) {
return res.status(400).json({ error: 'Name and price are required' });
}
FULL STACK DEVELOPMENT BIS601

const newProduct = {
id: idCounter++,
name,
price,
};
products.push(newProduct);
res.status(201).json(newProduct);
});
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});

7️. Discuss GraphQL vs REST architecture.


 GraphQL vs REST Architecture
Feature REST GraphQL
Multiple endpoints (URLs) Single endpoint (e.g., /graphql)
Data Fetching for different resources (e.g., that handles all queries and
/users, /posts). mutations.
Clients specify exactly what
Fixed, predefined responses
Request data they want in the query.
per endpoint. Client gets all
Structure Responses contain only
data the server sends.
requested fields.
Common problems: clients
Solves these problems by
Overfetching / often get more or less data
allowing precise queries with
Underfetching than needed, requiring
nested related data.
multiple requests.
No versioning needed; clients
Often requires versioning
ask for what they want, so new
Versioning (e.g., /api/v1/) to handle
fields can be added without
changes in API.
breaking clients.
Less flexible; server controls Highly flexible; clients control
Flexibility
response shape. data shape and can request
FULL STACK DEVELOPMENT BIS601

Feature REST GraphQL


multiple related resources in one
query.
Easier to start; REST Steeper learning curve due to
Learning Curve principles map well to HTTP new syntax and concepts
verbs and URLs. (queries, mutations, schema).
Well-established tooling, Caching is more complex;
Tooling and
HTTP caching (like GET requires special tools (e.g.,
Caching
requests) is easy. Apollo Client) and strategies.
Typically requires additional
Supports real-time data with
Real-time Data protocols (e.g., WebSockets)
built-in subscriptions feature.
alongside REST.
Returns detailed error
Uses HTTP status codes (404, information in the response
Error Handling
500, etc.). body, alongside partial data if
applicable.
When to Use Each?
REST:
 Simpler APIs with well-defined resources.
 When leveraging HTTP caching is important.
 When the client-server interaction is straightforward.
 When backward compatibility and stable APIs are needed.
GraphQL:
 Complex data requirements, especially with nested/related data.
 When clients need flexibility to request only the data they need.
 Rapid frontend development with evolving data needs.
 Real-time applications requiring subscriptions.

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


gracefully.
 Key Features
 Validates incoming JSON payloads with Joi (a popular validation library).
 Uses a centralized error-handling middleware.
FULL STACK DEVELOPMENT BIS601

 Sends meaningful error responses with appropriate HTTP status codes.


const express = require('express');
const Joi = require('joi');
const app = express();
const PORT = 3000;
app.use(express.json());
const productSchema = Joi.object({
name: Joi.string().min(3).max(30).required(),
price: Joi.number().positive().required(),
});
const products = [];
let idCounter = 1;
function validateBody(schema) {
return (req, res, next) => {
const { error } = schema.validate(req.body, { abortEarly: false });
if (error) {
const err = new Error('Validation error');
err.status = 400;
err.details = error.details.map(detail => detail.message);
return next(err);
}
next();
};
}
app.post('/products', validateBody(productSchema), (req, res, next) => {
const { name, price } = req.body;
const newProduct = { id: idCounter++, name, price };
products.push(newProduct);
res.status(201).json(newProduct);
});
app.get('/products', (req, res) => {
res.json(products);
});
app.use((err, req, res, next) => {
FULL STACK DEVELOPMENT BIS601

console.error(err);
const status = err.status || 500;
const response = {
message: err.message || 'Internal Server Error',
};
if (err.details) {
response.details = err.details;
}
res.status(status).json(response);
});
app.listen(PORT, () => {
console.log(`Server listening at http://localhost:${PORT}`);
});
Example Request & Error
POST /products
{
"name": "TV",
"price": -100
}
Response:
{
"message": "Validation error",
"details": ["\"price\" must be a positive number"]
}
FULL STACK DEVELOPMENT BIS601

Module - 5️
1. Explain the core components of MongoDB: Document, Collection, and
Database.
 Core Components of MongoDB
1. Document
 The basic unit of data in MongoDB.
 Similar to a row in a relational database, but more flexible.
 Stored in JSON-like format called BSON (Binary JSON).
 Consists of key-value pairs.
 Can have nested objects and arrays.
Example Document:
{
"_id": "507f1f77bcf86cd799439011",
"name": "Alice",
"age": 28,
"email": "[email protected]",
"address": {
"street": "123 Maple St",
"city": "Springfield"
}
}
2️. Collection
 A group of related documents.
 Analogous to a table in relational databases.
 Does not enforce schema, so documents in the same collection can have different
structures.
 Collections live inside databases.
Example: A collection named users might contain many documents like the example
above.
3️. Database
 A container for collections.
 One MongoDB server can have multiple databases.
 Each database is independent and has its own set of collections.
FULL STACK DEVELOPMENT BIS601

 Databases are like folders on a filesystem; collections are the files inside them.

2️. Write basic MongoDB queries for CRUD operations using Node.js.
const { MongoClient, ObjectId } = require('mongodb');
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const db = client.db('mydatabase');
const products = db.collection('products');
const newProduct = { name: 'Laptop', price: 999 };
const insertResult = await products.insertOne(newProduct);
console.log('Inserted product with ID:', insertResult.insertedId);
const allProducts = await products.find().toArray();
console.log('All products:', allProducts);
const id = insertResult.insertedId;
const oneProduct = await products.findOne({ _id: id });
console.log('Found product:', oneProduct);
const updateResult = await products.updateOne(
{ _id: id },
{ $set: { price: 899 } }
);
console.log('Updated count:', updateResult.modifiedCount);
// DELETE: Delete the product
const deleteResult = await products.deleteOne({ _id: id });
console.log('Deleted count:', deleteResult.deletedCount);
} finally {
await client.close();
}
}
run().catch(console.dir);
FULL STACK DEVELOPMENT BIS601

3️. How is data modeled in MongoDB? Demonstrate with a product


schema.
 How Data is Modeled in MongoDB
 Data is stored as documents (JSON-like objects).
 Documents live inside collections.
 Documents can have nested structures and arrays.
 MongoDB does not enforce a rigid schema (schema-less), allowing different
documents in the same collection to have different fields.
 However, you can define a schema at the application level (e.g., using Mongoose in
Node.js) for consistency and validation.
Example: Product Schema in MongoDB
Here's an example of what a product document might look like in MongoDB:
{
"_id": "507f1f77bcf86cd799439011",
"name": "Smartphone",
"price": 699.99,
"category": "Electronics",
"inStock": true,
"tags": ["mobile", "android", "touchscreen"],
"details": {
"brand": "ExampleBrand",
"model": "X1000",
"warranty": "1 year"
},
"ratings": [
{ "user": "user123", "score": 4, "comment": "Great phone!" },
{ "user": "user456", "score": 5, "comment": "Excellent value" }
]
}
Explanation:
Field Type Description
_id ObjectId Unique identifier (auto-generated by MongoDB)
name String Product name
FULL STACK DEVELOPMENT BIS601

Field Type Description


price Number Price of the product
category String Product category
inStock Boolean Availability
tags Array[String] Keywords for searching/filtering
details Object Nested object for product-specific details
ratings Array[Object] List of user ratings and comments

4️. Discuss the role of Mongoose in MERN applications.


 What is Mongoose?
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It
provides a higher-level abstraction on top of the MongoDB driver, making it easier to
work with MongoDB in Node apps.
Role of Mongoose in MERN Stack
1. Schema Definition & Data Modeling
 MongoDB itself is schema-less, but Mongoose lets you define schemas for your data
models (e.g., User, Product).
 This ensures your data follows a consistent structure and helps catch errors early.
2️. Validation
 Mongoose schemas support built-in validators (e.g., required fields, data types,
min/max values).
 You can define custom validation rules too.
3️. Middleware (Hooks)
 Supports pre/post middleware on operations like save, validate, remove.
 Useful for things like hashing passwords before saving a User, logging, or cascading
deletes.
4️. Convenient APIs
 Provides easy-to-use methods for CRUD operations (e.g., .find(), .save(),
.updateOne()).
 Supports advanced queries, population (joins), pagination, and more.
5️. Connection Management
FULL STACK DEVELOPMENT BIS601

 Handles connecting to MongoDB with features like automatic reconnection,


connection pooling, etc.
6️. Integration with Express
 Fits naturally in Express.js backend to handle the database layer.
 You define Mongoose models and use them in Express routes to persist and fetch data.

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


 What is Webpack?
Webpack is a module bundler for JavaScript applications. It takes all your JavaScript
files, CSS, images, and other assets, processes them, and bundles them into one or more
optimized files that browsers can efficiently load.
Role of Webpack in Front-End Development
1. Module Bundling
 Modern JavaScript apps use modules (e.g., ES6 import/export).
 Webpack resolves dependencies between modules and bundles them into one or more
files (called bundles).
 This reduces the number of HTTP requests by combining multiple files.
2️. Asset Processing
 Webpack can process CSS, SASS/LESS, images, fonts, and more using loaders.
 Transforms assets (e.g., compile SASS to CSS, optimize images).
3️. Code Splitting
 Breaks bundles into smaller chunks to load code on demand (lazy loading).
 Improves initial load times and performance.
4️. Development Server & Hot Module Replacement
 Provides a dev server with live reloading.
 Supports hot module replacement (HMR) so changes appear instantly without full page
reload.
5️. Optimizations
 Minifies and compresses code for production.
 Tree shaking: removes unused code.
 Cache busting via hashed filenames.

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


FULL STACK DEVELOPMENT BIS601

 Front-end Modules vs Back-end Modules


Aspect Front-end Modules Back-end Modules
Manage UI, user
Handle server logic, database
Purpose interactions, and client-side
operations, APIs, and business logic
logic

Environment Runs in the browser Runs on the server


JavaScript (with
JavaScript (Node.js), Python, Ruby,
Languages frameworks like React,
Java, etc.
Vue), HTML, CSS
UI components, state Database models, API
Common
management, utility routes/controllers, middleware,
Module Types
functions services
Express route handlers
React components
Examples (userRoutes.js), Mongoose models
(Button.js, Navbar.js)
(User.js)
Import/export controllers, services,
Module Import/export components
models using CommonJS or ES
Interaction or hooks, CSS modules
modules
Tools & Node.js module system, package
Webpack, Vite, Babel
Bundlers managers (npm/yarn)
Example Front-end Module
import React from 'react';
function Button({ onClick, label }) {
return <button onClick={onClick}>{label}</button>;
}
export default Button;
Example Back-end Module
const User = require('../models/User');
exports.getUser = async (req, res) => {
try {
const user = await User.findById(req.params.id);
if (!user) return res.status(404).send('User not found');
FULL STACK DEVELOPMENT BIS601

res.json(user);
} catch (error) {
res.status(500).send('Server error');
}
};

7️. Explain Hot Module Replacement (HMR) and its use in development.
 What is Hot Module Replacement (HMR)?
Hot Module Replacement (HMR) is a feature provided by modern bundlers like
Webpack that allows you to update modules in a running application without a full
page reload.
Instead of reloading the entire web page when you make changes to your code (e.g., CSS,
JavaScript), HMR only injects the updated modules into the app on the fly.
Why Use HMR?
 Faster feedback loop: See changes immediately without waiting for a full reload.
 Preserves app state: Since the page isn’t reloaded, you don’t lose UI state or form
data.
 Improves developer experience: Makes development smoother, especially in complex
apps like React.
 Efficient: Updates only the changed parts rather than rebuilding the whole bundle and
refreshing.
How It Works
1. You modify a source file (say a React component or CSS).
2. The bundler detects the change, recompiles only that module.
3. The updated module is pushed to the browser.
4. The app replaces the old module with the new one dynamically.
5. Your app updates UI instantly without a full reload.
Example Use Case
In React development, without HMR:
 You save a component file.
 The browser reloads.
 You lose the state (e.g., form inputs, navigation position).
With HMR:
FULL STACK DEVELOPMENT BIS601

 You save the component.


 Only that component’s code updates.
 The UI refreshes but your app state remains intact.
Summary Table
Feature Without HMR With HMR
Page reload on change Yes No
State preservation No Yes
Development speed Slower Faster
Developer experience Less smooth Much smoother

8. Write a build configuration using Webpack with DefinePlugin and


production optimization.
 Sure! Here’s a Webpack configuration example that includes:
 Using DefinePlugin to inject environment variables,
 Production optimizations like minification and mode: 'production',
 Basic handling for JavaScript and CSS.
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
mode: 'production', // enables minification & optimizations
entry: './src/index.js',
output: {
filename: 'bundle.[contenthash].js',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader',
FULL STACK DEVELOPMENT BIS601

},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader'],
},
],
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production'),
'process.env.API_URL': JSON.stringify('https://api.example.com'),
}),
new MiniCssExtractPlugin({
filename: 'styles.[contenthash].css',
}),
],
optimization: {
splitChunks: {
chunks: 'all',
},
minimize: true,
},
};
Explanation:
 mode: 'production' — Turns on built-in optimizations like minification and tree
shaking.
 DefinePlugin — Replaces process.env.NODE_ENV and process.env.API_URL in
your source code at build time with the specified values (helps React and other libs
optimize).
 MiniCssExtractPlugin — Extracts CSS into separate files instead of inline styles.
 splitChunks — Automatically splits vendor and common code into separate bundles
to optimize caching.
 filename: 'bundle.[contenthash].js' — Uses content-based hashing for cache busting.

You might also like