0% found this document useful (0 votes)
12 views

FSD-7m

The document contains various sections detailing web development concepts including a customer registration form, weather data fetching, ES6 features for React, event bubbling and capturing, promise handling with then() and catch(), JavaScript generators, JWT token generation and verification in a MERN stack application, dynamic list creation, and browser events. Each section provides code examples and explanations to illustrate the concepts. Overall, it serves as a comprehensive guide to modern JavaScript and web development practices.

Uploaded by

venkat Mohan
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)
12 views

FSD-7m

The document contains various sections detailing web development concepts including a customer registration form, weather data fetching, ES6 features for React, event bubbling and capturing, promise handling with then() and catch(), JavaScript generators, JWT token generation and verification in a MERN stack application, dynamic list creation, and browser events. Each section provides code examples and explanations to illustrate the concepts. Overall, it serves as a comprehensive guide to modern JavaScript and web development practices.

Uploaded by

venkat Mohan
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/ 14

1.​ Design of Registration form.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Customer Employee Registration Form </title>
</head>
<body>
<h2>Customer Registration</h2>
<form>
<label>Full Name:</label>
<input type="text" name="customer_name" required><br><br>

<label>Email:</label>
<input type="email" name="customer_email" required><br><br>

<label>Phone:</label>
<input type="tel" name="customer_phone" required><br><br>

<label>Address:</label>
<textarea name="customer_address" required></textarea><br><br>

<label>Department:</label>
<input type="text" name="employee_department" required><br><br>

<button type="submit">Register</button>
</form>
</body>
</html>
2.​ Weather data and display the temperature.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather App</title>
</head>
<body>
<h2>Current Weather</h2>
<p id="weather">Loading...</p>

<script>
const apiKey = "YOUR_API_KEY";
const city = "Salem"; // Change to your desired city

fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=
metric&appid=${apiKey}`)
.then(response => response.json())
.then(data => {
const temperature = data.main.temp;
const condition = data.weather[0].description;
document.getElementById("weather").innerText = `Temperature:
${temperature}°C, Condition: ${condition}`;
})
.catch(error => {
document.getElementById("weather").innerText = "Failed to load
weather data";
console.error("Error fetching weather data:", error);
});
</script>
</body>
</html>
3.​ Key ES6 features (like arrow functions, destructuring, and template literals)
that can improve React development, and how would refactor an existing
ES5-based component using ES6.
Key ES6 Features for React Development
ES6 (also known as ECMAScript 2015) introduces several features that
improve React development. Some key ones include:

Arrow Functions
●​ Shorter syntax for functions, reducing boilerplate code.
●​ Lexical this binding, which eliminates the need for .bind(this) in class
components.
Example:
const greet = name => `Hello, ${name}!`;
console.log(greet("React"));

Destructuring Assignment
●​ Makes it easy to extract values from arrays or properties from
objects.
●​ Useful for working with props and state in React components.
Example:
const user = { name: "Alice", age: 25 };
const { name, age } = user;
console.log(name, age);

Template Literals
●​ Allows embedding expressions inside string templates using backticks
(`).
●​ Useful for dynamically generating class names or inline styles in JSX.
Example:
const name = "React";
console.log(`Welcome to ${name}!`);
Refactoring an ES5 Component to ES6
Here’s an example of an ES5 React component refactored using ES6
features:
ES5 Version
var React = require('react');
var Greeting = React.createClass({
getInitialState: function() {
return { name: "World" };
},
render: function() {
return React.createElement('h1', null, 'Hello, ' + this.state.name + '!');
}
});
module.exports = Greeting;

Refactored ES6 Version


import React, { Component } from 'react';
class Greeting extends Component {
state = { name: "World" };
render() {
return <h1>Hello, {this.state.name}!</h1>;
}
}
export default Greeting;

4.​ What is Event Bubbling and Capturing in Js.


Event Bubbling and Capturing in JavaScript
Event handling in JavaScript follows a specific propagation pattern that
consists of two main phases: bubbling and capturing.
1. Event Bubbling
In this phase, an event starts at the target element (the element that
triggered the event) and bubbles up through its ancestors in the DOM
tree.
Example:
<div id="parent">
<button id="child">Click Me</button>
</div>
<script>
document.getElementById('parent').addEventListener('click', () => {
console.log('Parent Clicked');
});
document.getElementById('child').addEventListener('click', () => {
console.log('Child Clicked');
});
</script>

2. Event Capturing (Trickling)


In capturing mode, the event starts at the root and moves down to the
target element before triggering the event listener.
To enable capturing, the third parameter of addEventListener must be true.
Example:
<div id="parent">
<button id="child">Click Me</button>
</div>
<script>
document.getElementById('parent').addEventListener('click', () => {
console.log('Parent Captured');
}, true);
document.getElementById('child').addEventListener('click', () => {
console.log('Child Clicked');
});
</script>
5.​ How the then(), catch(), and QueueMicrotask() used in JavaScript
1. then() and catch() in JavaScript
then() and catch() are methods used with JavaScript Promises to
handle asynchronous operations efficiently.

then(): This method is used to execute a function when a Promise is


successfully resolved.
catch(): This method is used to handle errors in a Promise chain.

Example: Handling an API Request with fetch()


fetch('/api/issues')
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error("Network response was not ok");
}
})
.then(data => {
console.log("Data received:", data);
})
.catch(error => {
console.error("There was a problem with the fetch operation:", error);
});

2. QueueMicrotask() in JavaScript
queueMicrotask() is used to queue a function in the Microtask Queue,
which executes after the currently executing script but before any
next Macrotask (like setTimeout).
Example:
console.log("Start");
queueMicrotask(() => {
console.log("Inside Microtask Queue");
});
console.log("End");

Output:
Start
End
Inside Microtask Queue
6.​ Define JavaScript Generators and Parameter Passing.
1. JavaScript Generator Functions
Generator functions in JavaScript allow you to pause and resume
function execution using the yield keyword. They are defined using
an asterisk (*) after the function keyword.
Example:
function* simpleGenerator() {
yield "First";
yield "Second";
yield "Third";
}

const gen = simpleGenerator();


console.log(gen.next().value); // First
console.log(gen.next().value); // Second
console.log(gen.next().value); // Third
console.log(gen.next().done); // true

2. Parameter Passing in Generators


You can pass values to a generator using next(value), and it will
replace the last yield statement.
Example:
function* numberGenerator() {
const num1 = yield "Enter first number";
const num2 = yield "Enter second number";
return num1 + num2;
}

const gen = numberGenerator();


console.log(gen.next().value); // "Enter first number"
console.log(gen.next(5).value); // "Enter second number"
console.log(gen.next(10).value); // 15

Explanation:
gen.next().value starts the function and pauses at yield.
gen.next(5) resumes execution, replacing yield with 5.
gen.next(10) assigns 10 to num2 and returns the sum.
7.​ JWT Token Generation and Verification in a MERN Stack Application
JSON Web Tokens (JWT) are used for authentication in MERN stack
applications, ensuring secure communication between the client and
server.
1. Installing Dependencies
To generate and verify JWTs in a Node.js (Express) backend, install
the json web token package:
npm install jsonwebtoken dotenv
jsonwebtoken: For creating and verifying tokens.
dotenv: For managing environment variables securely.
2. Generating a JWT Token
In the backend, create an authentication route to generate a JWT:
Back end Code:
const express = require('express');
const jwt = require('jsonwebtoken');
const cors = require('cors');
require('dotenv').config();
const app = express();
app.use(express.json());
app.use(cors());

const SECRET_KEY = process.env.JWT_SECRET || 'your_secret_key';

// Generate JWT Token


app.post('/login', (req, res) => {
const { email, password } = req.body;

if (email === '[email protected]' && password === '123456') {


const token = jwt.sign({ email }, SECRET_KEY, { expiresIn: '1h' });
res.json({ token });
} else {
res.status(401).json({ message: 'Invalid credentials' });
}
});
// Protected Route
app.get('/protected', verifyToken, (req, res) => {
res.json({ message: 'Access granted!', user: req.user });
});

app.listen(5000, () => console.log('Server running on port 5000'));


3.Verify Token
const verifyToken = (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(403).json({ message: 'Token required'
});

jwt.verify(token, SECRET_KEY, (err, decoded) => {


if (err) return res.status(401).json({ message: 'Invalid token' });

req.user = decoded;
next();
});
};
4.Frontend (React) Overview for JWT Authentication
The frontend is responsible for:
●​ User Login → Sends email & password to the backend.
●​ Storing the JWT Token → Saves the token in localStorage after a
successful login.
●​ Sending Authenticated Requests → Adds the token in the request
header for protected API calls.
●​ Handling Responses → Displays a success message if access is granted,
otherwise shows an error.

5.Run the Application


Run the Java script code by:
node server.js
8.​ Dynamically Creating an Unordered List in JavaScript and Mutation Observer
in JavaScript
Dynamically Creating an Unordered List
The book describes dynamically generating elements using
JavaScript. In React, a similar approach is used to generate UI
elements based on data.
Example Using JavaScript
You can dynamically create an unordered list (<ul>) and populate it with list
items (<li>) like this:
// Create an unordered list
const ul = document.createElement("ul");
// List of items to add
const items = ["Apple", "Banana", "Cherry"];

items.forEach(item => {
const li = document.createElement("li"); // Create <li>
li.textContent = item; // Set text
ul.appendChild(li); // Append <li> to <ul>
});
document.body.appendChild(ul); // Append <ul> to the page

Output:
Apple
Banana
Cherry
Mutation Observer in JavaScript
A Mutation Observer allows tracking changes to the DOM (like node
insertions, removals, or attribute changes). This is useful for dynamically
updating content.

Example: Observing Changes to a <div>


// Select the target element
const target = document.getElementById("container");
// Create a Mutation Observer
const observer = new MutationObserver(mutations => {
console.log("Changes detected:", mutations);
});
// Start observing the target
observer.observe(target, { childList: true });
// Dynamically add an element after 2 seconds
setTimeout(() => {
const newElement = document.createElement("p");
newElement.textContent = "New Item Added!";
target.appendChild(newElement);
}, 2000);
observer.observe(targetNode, { childList: true, subtree: true });
9.​ What are JavaScript Browser Events?
●​ JavaScript browser events are triggered when users interact with the
browser window or elements within a webpage. These events help in
handling user interactions effectively.

Event Description

load Fires when the page is fully loaded.

resize Fires when the window is resized.

scroll Fires when the user scrolls within a


page.

focus Fires when an element gains focus.

blur Fires when an element loses focus.

online Fires when the browser goes


online.

offline Fires when the browser goes


offline.

Handling Browser Events in JavaScript:

Window Load Event:

window.addEventListener("load", function() {​
console.log("Page fully loaded!");​
});

Window Resize Event:

window.addEventListener("resize", function() {​
console.log("Window resized: ", window.innerWidth, "x",
window.innerHeight);​
});

Scroll Event:

window.addEventListener("scroll", function() {​
console.log("User scrolled the page!");​
});
Detecting Online/Offline Status:

window.addEventListener("online", function() {​
console.log("Back online!");​
});​
window.addEventListener("offline", function() {​
console.log("You are offline!");​
});

10.​ What are JavaScript Browser Events?​


UI (User Interface) events in JavaScript are actions that occur as a result of
user interactions or browser changes. These events allow developers to
create dynamic and interactive web applications.

Event Description

click Triggered when an element is


clicked.

mouseover Triggered when the mouse moves


over an element.

mouseout Triggered when the mouse leaves


an element.

keydown Triggered when a key is pressed.

keyup Triggered when a key is released.

change Triggered when an input field value


changes.

focus Triggered when an input field gains


focus.

blur Triggered when an input field loses


focus.
Handling UI Events in JavaScript:

Click Event:

document.getElementById("myButton").addEventListener("click",
function() {​
alert("Button Clicked!");​
});

Keydown Event:

document.addEventListener("keydown", function(event) {​
console.log("Key Pressed:", event.key);​
});

Mouseover Event:

document.getElementById("myDiv").addEventListener("mouseover",
function() {​
this.style.backgroundColor = "yellow";​
});

Event Delegation:

document.getElementById("parentList").addEventListener("click",
function(event) {​
if (event.target.tagName === "LI") {​
alert("List item clicked: " + event.target.textContent);​
}​
});

You might also like