Module - 1: 1. Explain Different Data Types in Javascript With Suitable Examples
Module - 1: 1. Explain Different Data Types in Javascript With Suitable Examples
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
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);
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.
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."
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.
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
Code Length Generally longer and more verbose More concise and readable
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
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
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
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
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;
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)
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}`);
});
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
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
},
{
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.