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

Fullstack Assignment PDF

The document provides comprehensive answers to web development modules covering JavaScript basics, DOM manipulation, React components, REST APIs, and MongoDB. It explains key concepts such as variable declaration differences, data types, event handling, and the MERN stack. Additionally, it discusses advanced topics like GraphQL, Webpack, and error handling in Express APIs.
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 views18 pages

Fullstack Assignment PDF

The document provides comprehensive answers to web development modules covering JavaScript basics, DOM manipulation, React components, REST APIs, and MongoDB. It explains key concepts such as variable declaration differences, data types, event handling, and the MERN stack. Additionally, it discusses advanced topics like GraphQL, Webpack, and error handling in Express APIs.
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

Full Answers for Web Development Modules

Module 1 - JavaScript Basics


1. Explain the difference between var, let, and const in JavaScript with examples.
In JavaScript, `var`, `let`, and `const` are used to declare variables, but they differ in terms of scope,
hoisting, and mutability.

- `var`: Function-scoped and hoisted to the top of its function. Variables declared with `var` can be
re-declared and updated.
Example:
```javascript
function exampleVar() {
var x = 1;
if (true) {
var x = 2;
[Link](x); // 2
}
[Link](x); // 2
}
```

- `let`: Block-scoped and not hoisted in the same way as `var`. It can be updated but not re-declared
in the same scope.
Example:
```javascript
function exampleLet() {
let x = 1;
if (true) {
let x = 2;
[Link](x); // 2
}
[Link](x); // 1
}
```

- `const`: Block-scoped like `let`, but the value cannot be re-assigned after initialization.
Example:
```javascript
const PI = 3.14;
// PI = 3.14159; // Error: Assignment to constant variable
```

2. Describe the different data types supported in JavaScript.


JavaScript supports two main categories of data types:

**Primitive Types:**
1. `Number` - Any numeric value. Example: `let a = 10;`
2. `String` - Textual data. Example: `let name = "Alice";`
3. `Boolean` - Logical value: `true` or `false`. Example: `let isValid = true;`
4. `Null` - Represents intentional absence of value. Example: `let x = null;`
5. `Undefined` - A variable declared but not assigned a value. Example: `let y;`
6. `Symbol` - Unique and immutable primitive useful for keys in objects.
7. `BigInt` - Large integers beyond the limit of `Number`.

**Non-Primitive Types:**
- `Object` - Key-value pairs. Example: `{ name: "John", age: 30 }`
- `Array` - Ordered list. Example: `[1, 2, 3]`
- `Function` - A block of code designed to perform a task.
Example:
```javascript
function greet() {
return "Hello";
}
```

3. What are JavaScript functions and how are they different from methods?
A **JavaScript function** is a reusable block of code designed to perform a specific task. Functions
can be defined and invoked independently.
Example:
```javascript
function add(a, b) {
return a + b;
}
[Link](add(2, 3)); // 5
```

A **method** is a function that is a property of an object.


Example:
```javascript
const calculator = {
multiply: function(x, y) {
return x * y;
}
};
[Link]([Link](4, 5)); // 20
```

**Difference:**
- Functions are standalone.
- Methods are associated with objects.

4. Illustrate the usage of loops and conditional statements in controlling program flow.
**Conditional Statements:**
Used to perform different actions based on different conditions.
Example:
```javascript
let age = 18;
if (age >= 18) {
[Link]("Eligible to vote");
} else {
[Link]("Not eligible");
}
```

**Loops:**
Used to execute a block of code repeatedly.

1. **for loop**
```javascript
for (let i = 0; i < 5; i++) {
[Link](i);
}
```

2. **while loop**
```javascript
let i = 0;
while (i < 5) {
[Link](i);
i++;
}
```

3. **do-while loop**
```javascript
let i = 0;
do {
[Link](i);
i++;
} while (i < 5);
```

5. How do arrays and objects differ in terms of structure and usage in JavaScript?
**Arrays** are ordered collections indexed by numbers, best for lists.
Example:
```javascript
let fruits = ["apple", "banana", "cherry"];
[Link](fruits[1]); // banana
```

**Objects** are collections of key-value pairs, best for storing structured data.
Example:
```javascript
let person = { name: "Alice", age: 25 };
[Link]([Link]); // Alice
```

**Key Differences:**
- Arrays use numerical indices; objects use named keys.
- Arrays maintain order; objects do not guarantee order.
- Arrays have methods like `push`, `pop`; objects do not.

Module 2 - DOM & Events


1. Define the Document Object Model (DOM). How is it structured?
The Document Object Model (DOM) is a programming interface for web documents. It represents
the structure of a web page as a tree of objects.

- Each element in the HTML document becomes a node in the DOM.


- The DOM allows scripts to update content, structure, and style dynamically.

Structure:
- Root Node: `document`
- HTML -> HEAD and BODY
- BODY -> elements like div, p, ul, etc.

Example:
```html
<html>
<body>
<h1>Hello</h1>
<p>World</p>
</body>
</html>
```
DOM Tree:
- document
- html
- body
- h1
-p

2. Explain how to select and manipulate DOM elements using JavaScript.


You can use JavaScript methods to select and manipulate DOM elements:

**Selection Methods:**
- `[Link]("id")`
- `[Link]("class")`
- `[Link]("selector")`
- `[Link]("selector")`

**Manipulation:**
- Change content:
```javascript
[Link]("title").innerText = "New Title";
```
- Change style:
```javascript
[Link]("p").[Link] = "blue";
```
- Add element:
```javascript
let newDiv = [Link]("div");
[Link](newDiv);
```
3. Describe different types of events in JavaScript and their use cases.
JavaScript events allow interaction with user actions.

Common Events:
- `click`: Triggered when an element is clicked.
- `mouseover`: When the mouse is over an element.
- `keydown`: When a keyboard key is pressed.
- `submit`: When a form is submitted.
- `load`: When a page or resource is loaded.

Example:
```javascript
[Link]("btn").addEventListener("click", function() {
alert("Button Clicked!");
});
```
Use cases include validating input, toggling elements, fetching data, etc.

4. What is event delegation, and why is it useful in large-scale applications?


Event delegation is a technique where you add a single event listener to a parent element instead of
multiple listeners to individual child elements.

It uses the concept of **event bubbling**.

Example:
```javascript
[Link]("list").addEventListener("click", function(e) {
if ([Link] === "LI") {
[Link]("Item clicked:", [Link]);
}
});
```
**Advantages:**
- Performance improvement
- Dynamically added elements also respond
- Cleaner code in large applications

5. How do event listeners improve interactivity in web applications?


Event listeners allow web pages to respond to user actions like clicks, typing, or form submissions,
thereby enhancing user experience.

Example:
```javascript
[Link]("button").addEventListener("click", () => {
alert("You clicked the button!");
});
```
They make applications dynamic and interactive-such as in form validation, navigation toggles, or
live search.

Module 3 - Forms & React Components


1. Explain the key components of the MERN stack and their roles in web development.
The MERN stack includes four technologies:

1. **MongoDB** - A NoSQL database for storing application data as JSON-like documents.


2. **[Link]** - A web application framework for [Link], handling routing and middleware.
3. **[Link]** - A front-end JavaScript library for building user interfaces.
4. **[Link]** - A JavaScript runtime for executing server-side code.

Together, they allow full-stack development using a single language: JavaScript.

2. Describe the process of building a React component using both class and functional
approaches.
**Class Component:**
```javascript
class Welcome extends [Link] {
render() {
return <h1>Hello, {[Link]}</h1>;
}
}
```

**Functional Component:**
```javascript
function Welcome(props) {
return <h1>Hello, {[Link]}</h1>;
}
```

With Hooks:
```javascript
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>Clicked {count} times</button>
);
}
```

3. How is data passed between parent and child components in React?


Data is passed from parent to child components using **props**.

Example:
```javascript
function Child(props) {
return <p>Hello {[Link]}</p>;
}

function Parent() {
return <Child name="Alice" />;
}
```
Props are **read-only**. To pass data back, callback functions can be used:
```javascript
function Parent() {
const handleClick = () => alert("Clicked!");
return <Child onClick={handleClick} />;
}
```

4. What is dynamic composition in React? Provide an example.


Dynamic composition refers to the ability to compose components dynamically using
`[Link]` or higher-order components.

Example:
```javascript
function Wrapper(props) {
return <div className="box">{[Link]}</div>;
}

function App() {
return (
<Wrapper>
<h1>Hello</h1>
<p>This is content inside Wrapper</p>
</Wrapper>
);
}
```
This allows for reusable layout and component structures.

5. Discuss the steps involved in enhancing and validating HTML forms using JavaScript and
React.
Steps:

1. **Create controlled inputs** using state:


```javascript
const [email, setEmail] = useState("");
<input value={email} onChange={(e) => setEmail([Link])} />
```

2. **Validate input** using conditions:


```javascript
const isValid = [Link]("@");
```

3. **Display error messages** dynamically:


```javascript
{!isValid && <span>Invalid Email</span>}
```

4. **Submit the form** and prevent default behavior:


```javascript
function handleSubmit(e) {
[Link]();
// Validation logic
}
```

React form libraries like `Formik` or `React Hook Form` also help in complex form handling.

Module 4 - React State & Express APIs


1. Explain the React component state and the concept of lifting state up.
**React State** is a built-in object that stores property values that belong to a component. It allows
components to create and manage their own data.

Example:
```javascript
const [count, setCount] = useState(0);
```
**Lifting State Up** refers to moving shared state to a common ancestor component so multiple
children can access and update it.

Example:
```javascript
function Parent() {
const [data, setData] = useState("");
return (
<>
<Input setData={setData} />
<Display data={data} />
</>
);
}
```
This ensures consistent state between child components.

2. Compare props and state in React with suitable examples.


**Props:**
- Passed from parent to child.
- Read-only.
- Used to configure a component.

Example:
```javascript
function Welcome(props) {
return <h1>Hello, {[Link]}</h1>;
}
```

**State:**
- Managed within the component.
- Can be changed using `setState` (class) or `useState` (function).
Example:
```javascript
const [count, setCount] = useState(0);
```

**Comparison:**
- Props make components dynamic from the outside.
- State makes components dynamic from the inside.

3. What is a REST API? How is it created using Express?


**REST (Representational State Transfer)** is an architectural style for designing networked
applications using HTTP methods.

To create a REST API in Express:


```javascript
const express = require("express");
const app = express();
[Link]([Link]());

[Link]("/users", (req, res) => {


[Link](users);
});

[Link]("/users", (req, res) => {


[Link]([Link]);
[Link](201).send("User added");
});

[Link](3000);
```
Each route corresponds to a specific CRUD operation.

4. Describe how error handling is implemented in Express APIs.


Error handling in Express can be done using middleware.
Example:
```javascript
[Link]((err, req, res, next) => {
[Link]([Link]);
[Link](500).send("Something broke!");
});
```

Try-catch blocks can be used in route handlers:


```javascript
[Link]("/data", async (req, res, next) => {
try {
const result = await fetchData();
[Link](result);
} catch (err) {
next(err); // Forward to error middleware
}
});
```

5. What is GraphQL and how does it differ from REST?


**GraphQL** is a query language for APIs and a runtime for fulfilling those queries with your existing
data.

**Differences from REST:**


- In REST, each endpoint returns fixed data. In GraphQL, clients specify the exact data they need.
- REST uses multiple endpoints; GraphQL uses a single endpoint.
- GraphQL reduces over-fetching and under-fetching of data.

Example Query:
```graphql
{
user(id: "1") {
name
email
}
}
```

It responds with only the requested fields.

Module 5 - MongoDB & Webpack


1. Describe the document model of MongoDB and how it differs from relational databases.
MongoDB is a NoSQL database that stores data in a flexible, JSON-like format called BSON.

**Document Model:**
- Data is stored in documents (like objects), which are grouped into collections.
- No need for fixed schema, supports nested fields and arrays.

Example document:
```json
{
"name": "Alice",
"age": 30,
"skills": ["JS", "React"]
}
```

**Differences from Relational DB:**


- No joins; data can be embedded.
- Schema-less, vs. rigid schemas in SQL.
- Uses documents instead of rows and tables.

2. Explain the CRUD operations in MongoDB using Mongo Shell or [Link] driver.
CRUD = Create, Read, Update, Delete

Using Mongo Shell:


```javascript
// Create
[Link]({ name: "Alice", age: 25 });

// Read
[Link]({ name: "Alice" });

// Update
[Link]({ name: "Alice" }, { $set: { age: 26 } });

// Delete
[Link]({ name: "Alice" });
```

Using [Link] (MongoDB native driver):


```javascript
const user = { name: "Bob" };
await [Link]("users").insertOne(user);
```

3. What is the purpose of Webpack in full-stack development?


Webpack is a static module bundler for JavaScript applications.

**Purpose:**
- Bundles JavaScript, CSS, HTML, and assets.
- Transpiles code using loaders (e.g., Babel).
- Optimizes code for production (minification, tree shaking).

It allows full-stack developers to manage and bundle front-end assets efficiently.

4. Discuss the process of hot module replacement (HMR) and its benefits during
development.
**Hot Module Replacement (HMR)** allows updated modules to be replaced in a running app
without a full reload.

**Benefits:**
- Preserves app state during updates.
- Speeds up development.
- Improves productivity and feedback loop.

Example in Webpack config:


```javascript
devServer: {
hot: true,
}
```

5. How do you configure schema initialization and data access in MongoDB with [Link]?
Using Mongoose (an ODM for MongoDB):

1. **Define schema:**
```javascript
const mongoose = require("mongoose");
const UserSchema = new [Link]({
name: String,
age: Number
});
```

2. **Create model:**
```javascript
const User = [Link]("User", UserSchema);
```

3. **Connect and use:**


```javascript
[Link]("mongodb://localhost/mydb");
const user = new User({ name: "Alice", age: 25 });
[Link]();
```
Mongoose ensures data conforms to a defined schema before storing.

You might also like