Advanace Web Devlopment
Advanace Web Devlopment
<!DOCTYPE>
<html>
<head>
<title>HTML, Hello World</title>
</head>
<body>
<h1>Welcome To My Page</h1>
<p>Hello World</p>
</body>
</html>
<b> This is a physical tag, which is used to bold the text written between it.
<strong> This is a logical tag, which tells the browser that the text is important.
<big> This tag is used to increase the font size by one conventional unit.
<small> This tag is used to decrease the font size by one unit from base font size.
1) <div> Tag - The <div> tag is a block-level element used to group larger
sections of content. It creates a distinct section on a web page that can be
styled with CSS or manipulated with JavaScript.
Characteristics:
a) It starts on a new line and takes up the full width available.
b) Commonly used for layout purposes or to wrap sections of a page,
such as headers, footers, or main content areas.
<div class="container">
<h1>Welcome to My Website</h1>
<p>This is a paragraph inside a div.</p>
</div>
2) <span> Tag - The <span> tag is an inline element used to group small
portions of text or other inline elements. It does not create a new line and
only takes up as much width as its content.
Characteristics:
a) It is useful for styling or applying behavior to a specific part of text
without affecting the flow of the surrounding content.
b) Often used for highlighting text or adding styles to parts of a
sentence.
<p>This is a
within a paragraph.</p>
Structured Element in HTML5:
1) <header> – This is the top section of a webpage or a part of a page. It
usually has a logo, a title, and navigation links. You can have multiple
<header> elements if different sections need their own headers.
2) <footer> – This is the bottom section of a page or a part of a page. It often
contains copyright information, contact details, social media links, or extra
navigation. Like <header>, you can use multiple <footer> elements.
3) <section> – This is used to divide a webpage into different parts. Each
section focuses on a specific topic and usually has a heading (like <h1> or
<h2>). A blog post, for example, may have sections for the introduction,
main content, and conclusion.
4) <article> – This is for content that can stand on its own, like a blog post,
news article, or forum post. Unlike <section>, an <article> is a complete
piece of content by itself.
5) <nav> – This is used for navigation menus. It contains links that help users
move around the website. Only main navigation links should go inside
<nav>, not every link on the page.
6) <aside> – This is for content that is related to, but not part of, the main
content. It is often used for sidebars, ads, extra links, or author details.
Inside an article, it might contain notes or references.
7) <figure> – This is a container for images, diagrams, videos, or other media.
It keeps these elements organized and linked with captions.
8) <figcaption> – This is used inside <figure> to provide a caption or
description for the image or media. It helps explain what the image is
about.
9) <main> – This holds the main content of the webpage. It should not include headers,
footers, sidebars, or navigation menus—only the important content that the page is
about.
10) <address> – The <address> tag is used to provide contact information for the author,
organization, or owner of a webpage or article. It typically includes details like an
email address, phone number, physical address, or website link.
HTML5 Multimedia and Graphics Elements
1) <audio> – This element allows embedding audio files into a webpage,
enabling users to listen to music, podcasts, or other sound clips directly
from the browser. It supports multiple formats like MP3, Ogg, and WAV,
and provides controls for play, pause, and volume.
2) <video> – Similar to <audio>, this element is used to embed video
content, supporting formats like MP4, WebM, and Ogg. It includes built-in
controls for playback, volume, fullscreen mode, and subtitles, ensuring a
seamless user experience.
3) <source> – This tag is used within <audio> or <video> to define multiple
media sources. By listing different formats, browsers can select the best-
supported option, ensuring compatibility across devices.
4) <track> – Enhancing accessibility, the <track> element allows the addition
of captions, subtitles, or metadata to videos. It supports different kinds of
text tracks, such as subtitles for different languages or descriptions for
visually impaired users.
5) <canvas> – A versatile drawing surface that enables the creation of
graphics, animations, charts, and game visuals using JavaScript. It provides
a blank space where developers can dynamically render 2D or 3D graphics
via WebGL.
6) <svg> – Unlike <canvas>, which is pixel-based, <svg> is a markup-based
format for scalable vector graphics. It allows the creation of high-quality,
resolution-independent images, making it ideal for logos, icons, and
interactive visuals.
7) <figure> – This semantic container groups media elements like images,
videos, and charts, helping to associate them meaningfully with
surrounding content. It improves structure and accessibility in web design.
8) <figcaption> – Used within a <figure>, this element provides a descriptive
caption or explanation for the enclosed media. It enhances readability and
helps users understand the significance of the visual content.
HTML Form:
HTML forms are simple form that has been used to collect data from the users.
HTML form has interactive controls and various input types such as text,
numbers, email, password, radio buttons, checkboxes, buttons, etc. We can see
its application in multiple sites, including registration forms, customer feedback
forms, online survey forms and many more.
Grid Layout:
CSS Grid Layout is used to design responsive web layouts with rows and
columns. It allows you to place items exactly where you want, making it
easier to create flexible and modern web pages.
Unlike older methods like floats, CSS Grid gives more control over alignment
and adapts well to different screen sizes.
Grid Property:
1) display - This fundamental property transforms an HTML element into a
grid container, enabling all grid functionality for that element and its
direct children. Example: display: grid;.
2) grid-template-columns - This defines the structure of the grid’s
columns by specifying their widths and how many columns there are.
You can use units like px, %, fr (fractional units), or auto. For example,
grid-template-columns: 1fr 2fr 1fr; creates three columns where the
middle one is twice as wide as the others.
3) grid-template-rows - This works the same way as grid-template-
columns, but controls the height and number of rows. You can set row
sizes in px, %, fr, or auto. For example, grid-template-rows: 100px auto
1fr; creates three rows with different heights.
4) grid-template-areas - This allows you to visually map out your grid
using named areas, making the layout easier to read and manage. You
assign names to sections like "header", "sidebar", and "content", and
then place items into these areas using grid-area. This approach works
especially well for page layouts.
5) grid-template - This is a shorthand that lets you define grid-template-
rows, grid-template-columns, and grid-template-areas all at once. This
is helpful for combining structure and named areas in one place, but it
can get long for complex layouts.
6) column-gap - This property defines the amount of space between
columns in the grid. For example, column-gap: 20px; leaves 20 pixels of
space between each column, making it easy to add consistent spacing
between columns.
7) row-gap - This property defines the space between rows in the grid. For
example, row-gap: 15px; would leave 15 pixels between each row. This
is useful for adding spacing without extra margins.
8) gap - This is a shorthand for setting both row-gap and column-gap in
one go. You can set them independently like gap: 15px 20px; (rows
then columns) or just gap: 20px; to apply the same spacing in both
directions.
9) grid-auto-columns - When your grid adds new columns automatically (if
there are more items than defined columns), this property defines how
wide those extra columns should be. For example, grid-auto-columns:
100px; makes all auto-added columns 100px wide.
10) grid-auto-rows - Similar to grid-auto-columns, this defines the height
of automatically created rows when grid items are placed outside the
explicitly defined grid structure. For example, grid-auto-rows: 80px;
would make all such rows 80 pixels tall.
11) grid-auto-flow - This controls how items are automatically placed into
the grid, either filling in row by row (row) or column by column
(column). The dense keyword tries to fill all gaps by backfilling smaller
items into empty spaces, which can change the visual order.
12) grid - This is a super shorthand that lets you set both explicit (template
rows, columns, areas) and implicit (auto-rows, auto-columns, auto-
flow) grid properties in a single declaration. It’s powerful but often less
readable than using individual properties.
13) grid-column-start - This property defines where a grid item starts
horizontally, by referring to grid lines (the vertical dividers between
columns). For example, grid-column-start: 2; places the item starting at
the second column line.
14) grid-column-end - This defines where a grid item ends horizontally,
again using grid lines. For example, grid-column-end: 4; would make the
item stretch to the fourth column line.
15) grid-row-start - This defines where a grid item starts vertically, based
on row lines. For example, grid-row-start: 1; places the item at the first
row line.
16) grid-row-end - This defines where a grid item ends vertically, also
using row lines. For example, grid-row-end: 3; would make the item
span from row 1 to row 3.
17) grid-column - This is a shorthand for defining both grid-column-start
and grid-column-end in one property. For example, grid-column: 2 / 4;
places the item across columns 2 and 3, ending at line 4.
18) grid-row - This is a shorthand for defining both grid-row-start and grid-
row-end together. For example, grid-row: 1 / 3; spans the item across
two rows.
19) grid-area - This versatile property can either assign a name to an item
(for use with grid-template-areas) or define all four positioning values
(row start, column start, row end, column end) at once. Example: grid-
area: 1 / 2 / 3 / 4;.
20) justify-content - This property horizontally aligns the entire grid inside
its container when the grid is smaller than the container. Values include
start, end, center, stretch, space-around, space-between, and space-
evenly.
21) align-content - Similar to justify-content, this property vertically aligns
the entire grid when the grid’s height is smaller than the container. It
uses the same alignment values like start, end, center, and stretch.
22) place-content - This is a shorthand for setting both align-content and
justify-content at once. For example, place-content: center space-
between; centers vertically and spaces items evenly horizontally.
23) align-items - This property vertically aligns the content inside all grid
items within their individual cells. Items can align to start, end, center,
or stretch to fill the whole cell.
24) justify-items - This property horizontally aligns the content inside all
grid items within their cells. It uses the same values as align-items like
start, end, center, or stretch.
25) align-self - This overrides align-items for a specific grid item, letting
you individually control vertical alignment for just that item. Example:
align-self: center; centers it vertically.
26) justify-self - This overrides justify-items for a specific grid item, letting
you control its horizontal alignment independently. Example: justify-
self: end; pushes the item to the right side of its cell.
27) place-self - This shorthand sets both align-self and justify-self for a
specific item in one go. For example, place-self: start center; vertically
aligns to the top and horizontally centers the content.
EXAMPLE:
<!DOCTYPE html>
<html>
<head>
<style>
.grid-container {
display: grid;
grid-template-columns: 1fr 1fr 1fr; /* Three equal columns */
grid-template-rows: 100px 200px; /* Two rows with specific
heights */
gap: 20px; /* Space between all grid items
*/
background-color: #f0f0f0;
padding: 20px;
}
.grid-item {
background-color: #3498db;
color: white;
border-radius: 5px;
padding: 20px;
font-size: 20px;
text-align: center;
}
2) Children/Flex-items Properties:
a) order - This property changes the visual order of an item within the flex
container without changing the order in the HTML itself. Items with
lower order values appear first, and higher values appear later, giving
you control over layout independent of source order.
b) flex-grow - This property allows a flex item to grow and take up extra
space when there is unused space in the flex container. Items with a
higher flex-grow value take up more space compared to items with a
lower value.
c) flex-shrink - This property controls how much a flex item shrinks when
there isn’t enough space in the container. Items with higher flex-shrink
values shrink more than those with lower values when space is limited.
d) flex-basis - This property defines the initial size of a flex item before any
growing or shrinking happens. It can be set using any size unit (like px,
%, rem, or auto), and serves as the item’s starting size.
e) flex - This shorthand property combines flex-grow, flex-shrink, and flex-
basis into a single, convenient line. For example, flex - 1 0 auto means
the item can grow, won’t shrink, and starts at its natural size.
f) align-self - This property lets you override the align-items setting for an
individual item, allowing it to have a different alignment along the cross
axis than the other items in the container. It’s useful when you want
one item to stand out or align differently from the rest.
EXAMPLE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flexbox Example</title>
<style>
.container {
display: flex; /* Enables Flexbox */
flex-direction: row; /* Items placed in a row (horizontal) */
justify-content: space-between; /* Items spread out with space between
*/
align-items: center; /* Items vertically centered */
height: 200px; /* Just to give container height */
border: 2px solid black; /* Border to see the container */
padding: 10px;
}
.item {
background-color: lightblue; /* Background color for items */
padding: 20px;
border: 1px solid blue; /* Border to see each item */
text-align: center; /* Center text in items */
flex-grow: 1; /* Each item can grow equally */
margin: 0 10px; /* Add spacing between items */
}
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
</div>
</body>
</html>
Features of CSS Flexbox:
1) One-dimensional layout - Flexbox is designed to lay out items along a
single axis at a time — either a horizontal row or a vertical column. It’s
perfect for simpler layouts like navbars, lists, or small sections where you
only need to control one direction.
2) Flexible sizing - Flex items can grow to fill extra space or shrink to avoid
overflow, depending on the available space in the container. This allows
your layout to automatically adjust to different screen sizes without
manually setting widths or heights.
3) Easy alignment - Flexbox makes it easy to align items along both the main
axis (horizontal or vertical) and the cross axis (the other direction). You
can center items, push them to the edges, or spread them evenly with
just a few properties.
4) Space distribution - Flexbox gives you control over how space is
distributed between items. With properties like justify-content, you can
easily spread items evenly, add space only between items, or center
everything inside the container.
5) Automatic wrapping - If there are too many items to fit in one line,
Flexbox can wrap items onto additional lines automatically (when you use
flex-wrap), making it useful for responsive designs where space is limited.
6) Reordering without HTML changes - With the order property, you can
change the visual order of flex items without changing their actual order
in the HTML file. This makes it easier to rearrange content for different
screen sizes or layouts.
7) Alignment flexibility for individual items - Flexbox allows individual items
to have different alignments from the rest using align-self, so you can
fine-tune the positioning of special items without affecting others.
8) Space-efficient design - Flexbox automatically ensures that available
space is efficiently used. Items can grow to fill space or shrink to fit tighter
areas, giving you better control over spacing without fixed dimensions.
9) Built-in responsiveness - Flexbox makes responsive design much easier
compared to older techniques like floats. By combining flex-grow, flex-
shrink, and flex-basis, items automatically adjust to different screen sizes,
reducing the need for media queries.
10) Shorthand properties for simplicity - Flexbox includes handy shorthand
properties like flex (for growth, shrink, and basis) and flex-flow (for
direction and wrapping), which let you write cleaner and shorter CSS
code.
CSS Preprocessor:
CSS preprocessors are tools that extend the functionality of regular CSS. They
allow developers to write styles using programming-like features such as
variables, nesting, functions, and reusable blocks of code. Preprocessors make
CSS easier to manage, especially for large projects, by adding structure and
reducing repetition. However, browsers cannot read preprocessor code directly,
so it must be compiled into regular CSS before being used on websites.
Features of SASS:
2) Variables in Sass - In Sass, variables let you store values (like colors,
fonts, or sizes) and reuse them throughout your stylesheet. This makes
your CSS more manageable, consistent, and easier to update.
EXAMPLE:
// Declare variable
$primary-color: #4CAF50;
button {
// Use variable
background-color: $primary-color;
color: white;
}
3) Nesting in Sass - In Sass, nesting allows you to write CSS rules inside
other rules, following the same structure as your HTML. This makes your
stylesheets more organized and easier to read, especially when dealing
with nested elements like menus, cards, or forms.
Style.scss Style.css
4) Mixins in Sass - Mixins in Sass are reusable chunks of styles that you can
define once and use anywhere. They make it easy to apply the same set
of styles across multiple selectors, with the flexibility to accept
parameters (like arguments in a function).
Style.scss Style.css
5) Functions in Sass - Sass functions are reusable blocks of logic that return
a value. Unlike mixins (which output CSS rules), functions are used inside
properties to calculate or generate values.
EXAMPLE:
// Declare function
@function calculateSpacing($base, $multiplier) {
// Use function
.container {
padding: calculateSpacing(20px, 4); // This will return 80px
}
.large-container {
padding: calculateSpacing(30px, 5); // This will return 100px (capped by the
if statement)
}
6) Imports & Partials in Sass - Sass offers a cleaner way to organize large
stylesheets by splitting them into smaller files, which can be combined
using @import (or in modern Sass, @use and @forward).
A partial is just a Sass file whose filename starts with an underscore (_)
for example: _buttons.scss (Partial), _header.scss (Partial).
The @import rule in Sass allows you to include the content of one file
into another. It helps break a big stylesheet into smaller, manageable
pieces.
_button.scss:
button {
background-color: blue;
color: white;
}
_header.scss:
header {
background-color: grey;
padding: 20px;
}
Main.scss:
// main.scss
@import 'buttons';
@import 'header';
body {
font-family: Arial, sans-serif;
}
7) Inheritance in Sass - Inheritance in Sass allows you to share styles
between selectors using the @extend directive. This is useful when
multiple elements share common styles — you can define the common
styles once and then "extend" them into other selectors.
EXAMPLE:
body {
font-family: Arial, sans-serif;
}
1) Color Functions - These help you modify colors - lighten, darken, etc.
EXAMPLE:
button {
background-color: lighten(#3498db, 10%);
}
str-length() str-length("Hello") 5
EXAMPLE:
p{
content: quote("Welcome");
}
3) Numeric Functions - These handle numbers - useful for calculations.
round() round(4.3) 4
ceil() ceil(4.3) 5
floor() floor(4.8) 4
EXAMPLE:
div {
width: calc(percentage(0.5) - 10px); // You can calculate values using
percentage()
}
div{
padding: nth($list, 2); // 15px
}
5) Map Function - A map in SCSS (SASS) is a collection of key-value pairs.
primary, secondary, and danger are keys. Each key points to a value (a
color in this case).
Example:
$colors: (
primary: #3498db,
secondary: #2ecc71
);
button {
background-color: map-get($colors, primary); // #3498db
}
6) Introspection Functions - These check things like type and if values exist.
unit() unit(10px) px
1) Introduction to Promises:
In JavaScript, Promises are used to handle asynchronous operations, which
are tasks that take time to complete, like fetching data from a server or
reading a file. The main reason we use promises is to avoid "callback hell" -
a messy situation where you have callbacks inside callbacks, making the
code hard to read and maintain.
A promise is like a guarantee that some work will either, Complete
successfully or Fail In both cases, the subscriber (your code) will be notified
so you can react to the result.
Syntax:
EXAMPLE:
let promise = new Promise((resolve, reject) => {
let success = 0;
if (success) {
resolve("Task completed!");
} else {
reject("Task failed!");
}
});
promise.then((message) => {
console.log("Success:", message);
});
promise.catch((error) => {
console.error("Error:", error);
});
Rather using promise variable separately for then and catch you can also
chain them which is called chaining .then and .catch like as
promise
.then((message) => {
console.log("Success:", message);
})
.catch((error) => {
console.error("Error:", error);
});
Promises Chaining:
We can chain promises and make them pass the resolved values to one
another. The idea is to pass the result through the chain of .then
handlers. Here is the flow of execution:
1. The initial promise resolves in 1 second (Assumption).
2. The next .then() handler is then called, which returns a new promise
and gets the result of the previous one.
3. The next .then() gets the result of the previous one and this keeps on
going.
Every call to .then() returns a new promise whose value is passed to the
next one and so on.
We can even create custom promises inside .then().
Example:
fetchData
.then((data) => {
console.log(data); // "Data fetched"
return "Processing data";
})
.then((processMessage) => {
console.log(processMessage); // "Processing data"
return "Data processed";
})
.then((finalMessage) => {
console.log(finalMessage); // "Data processed"
})
.catch((error) => {
console.error("Error:", error); // Catch any error in the chain
});
Promise API:
resolve(“value2”);
}, 2000);
});
EXAMPLE:
harry().then(alert);
So, async ensures that the function returns a promise and wraps non-
promises in it.
await keyword - There is another keyword called await that works only
inside async functions. The await keyword makes JavaScript wait until the
promise settles and returns its value. It’s just a more elegant syntax of
getting the promise result than .then(), but it’s easier to read and write.
EXAMPLE:
let value = await promise;
Complete Code async/await:
async function harry() {
let delhiWeather = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("27 Deg")
}, 2000)
})
// delhiWeather.then(alert)
// bangaloreWeather.then(alert)
console.log("Fetching Delhi Weather Please wait ...")
let delhiW = await delhiWeather
console.log("Fetched Delhi Weather: " + delhiW)
console.log("Fetching Bangalore Weather Please wait ...")
let bangaloreW = await bangaloreWeather
console.log("Fetched Bangalore Weather: " + bangaloreW)
return [delhiW, bangaloreW]
}
a.then((value)=>{
console.log(value)
})
Arrow Function:
An arrow function is a shorter syntax for writing functions in JavaScript.
Introduced in ES6, arrow functions allow for a more concise and readable
code, especially in cases of small functions. Unlike regular functions, arrow
functions don’t have their own this, but instead, inherit it from the
surrounding context.
a) Arrow functions are written with the => symbol, which makes them
compact.
b) They don’t have their own this. They inherit this from the surrounding
context.
c) For functions with a single expression, the return is implicit, making the
code more concise.
d) Arrow functions do not have access to the arguments object, which is
available in regular functions.
2) Arrow Function with Block body - An arrow function with a block body
uses curly braces {} to define the function body. When using a block body,
you must use the return keyword explicitly if you want to return a value.
EXAMPLE:
const sum = (a, b) => {
const result = a + b;
return result;
};
console.log(sum(5,5));
3) Arrow Function without Parameters - An arrow function without
parameters is defined using empty parentheses (). This is useful when
you need a function that doesn’t require any arguments.
EXAMPLE:
const gfg = () => {
console.log( "Hi from GeekforGeeks!" );
}
gfg();
EXAMPLE:
const square = x => {
x * x;
}
console.log(square(4));
EXAMPLE:
const con = (x, y, z = 30) => {
console.log(x + " " + y + " " + z);
}
con(10, 20);
setTimeout(() => {
console.log(`The name is ${this.name}\nThe role is ${this.role}`)
}, 2000)
}
}
console.log(x.name, x.exp)
x.show()
In this code, the show method is part of the object x, so when x.show() is
called, this correctly refers to x. Inside show, you have a setTimeout, and
inside it, you used an arrow function. This is important because arrow
functions do not have their own this — they inherit this from the outer
function (in this case, show). That means this inside the setTimeout arrow
function still refers to x, so this.name is "Anmol" and this.role is "Js
Developer". If you used a regular function instead of an arrow function
inside setTimeout, this would default to the global object (like window),
and this.name and this.role would be undefined. This is the key benefit of
using arrow functions in cases like this — they preserve the correct this
without needing .bind(), making the code cleaner and easier to
understand.
JavaScript Template Literal:
A JavaScript template literal is a way to create strings that allows for
embedded expressions, multi-line strings, and string interpolation using
backticks (``). Unlike regular strings, template literals can dynamically insert
variables or expressions directly into the string using ${} syntax.1)
EXAMPLE:
const poem = `Roses are red,
Violets are blue,
JavaScript is awesome,
And so are you!`;
console.log(poem);
5) Loops with Templates - Template literals work seamlessly with loops and
array methods, especially methods like map(), to generate dynamic lists
directly inside the template. For example, you can loop over an array of
items and format each one with a prefix or bullet point, then combine all
of them into a single string. This is particularly helpful for creating lists,
menus, or data tables dynamically.
EXAMPLE:
const items = ["apple", "banana", "cherry"];
const list = `Items: ${items.map(item => `\n- ${item}`)}`;
console.log(list);
6) Embedding Functions - You can also call functions directly inside a
template literal. This allows you to process or format values on the fly
before they are inserted into the final string. For example, you can apply
functions to capitalize text, format dates, or transform user input right at
the point of insertion. This keeps the code concise and expressive, since
all the logic is directly within the template.
EXAMPLE:
const toUpper = str => str.toUpperCase();
const s = `Shouting: ${toUpper("hello")}`;
console.log(s);
Destructuring in JavaScript:
Destructuring Assignment is a JavaScript expression that allows to unpack of
values from arrays, or properties from objects, into distinct variables data
can be extracted from arrays, objects, and nested objects, and assigned to
variables.
// Destructuring
let [fruit1, fruit2] = fruits;
console.log(fruit1, fruit2); // Output: Bananas Oranges
2) Skipping Array Values - With array destructuring, you can skip values you
don’t need by leaving empty commas in the destructuring pattern. This is
useful when you only care about certain elements in the array and want
to ignore the rest.
EXAMPLE:
// Create an Array
const moreFruits = ["Bananas", "Oranges", "Apples", "Mangos"];
// Destructuring
let [fruit3, , , fruit4] = moreFruits; // Skipping some values
console.log(fruit3, fruit4); // Output: Bananas Mangos
3) The Rest Property - The rest property (...rest) in array destructuring lets
you capture all remaining items into a new array after specific elements
have been destructured. This is useful when you need to separate the
first few items from the rest of the array.
EXAMPLE:
// Create an Array
const numbers = [10, 20, 30, 40, 50, 60, 70];
// Destructuring
const [a, b, ...rest] = numbers;
console.log(a, b); // Output: 10 20
console.log(rest); // Output: [30, 40, 50, 60, 70]
// Destructing
[firstName, lastName] = [lastName, firstName];
console.log(firstName, lastName); // Output: Doe John
// Destructuring
let { firstName: fName, lastName: lName } = person;
console.log(fName, lName); // Output: John Doe
// Destructuring
let [a1, a2, a3, a4, a5] = name;
console.log(a1, a2, a3, a4, a5); // Output: W 3 S c h
UNIT 2
Frontend Framework:
Introduction to ReactJS:
ReactJS is a free and open-source front-end JavaScript library which is used to
develop various interactive user-interfaces. It is a simple, feature rich and
component based UI library.
When we say component based, we mean that React develops applications
by creating various reusable and independent codes. ReactJS can be used to
develop small applications as well as big, complex applications.
Feature of ReactJS:
1) Component Based − ReactJS makes use of multiple components to build
an application. These components are independent and have their own
logic which makes them reusable throughout the development process.
This will drastically reduce the application's development time.
2) Better and Faster Performance − ReactJS uses Virtual DOM. Virtual DOM
compares the previous states of components of an application with the
current states and only updates the changes in Real DOM. Whereas,
conventional web applications update all components again. This helps
ReactJS in creating web applications faster.
3) Extremely Flexible − React allows developers and teams to set their own
conventions that they deem are best suited and implement it however
they see fit, as there are no strict rules for code conventions in React.
4) Creates dynamic applications easily − Dynamic web applications require
less coding while offering more functionality. Thus, ReactJS can create
them easily.
5) Develops Mobile Applications as well − Not only web applications, React
can also develop mobile applications using React Native. React Native is
an open-source UI software framework that is derived from React itself. It
uses React Framework to develop applications for Android, macOS, Web,
Windows etc.
6) Debugging is Easy − The data flow in React is unidirectional, i.e., while
designing an app using React, child components are nested within parent
components. As the data flows is in a single direction, it gets easier to
debug errors and spot the bugs.
cd <<Application_Name>>
npm start
ReactJS Installation
You can modify the application according to your preferences and change
the code accordingly.
App.js:
import './App.css';
function App() {
const pstyle = {
backgroundColor: 'purple',
fontSize: '20px',
color: 'yellow',
textAlign:'left',
};
return (
<div className="App">
<h1 className="text-center">Hello World</h1>
<p style={pstyle}>Lorem ipsum dolor sit amet consectetur adipisicing elit.
Quae praesentium sunt veritatis harum illo. Facere cupiditate saepe asperiores
illum earum?</p>
</div>
);
}
export default App;
Index.js:
reportWebVitals();
Map() method:
map() method in React is used to loop through an array and create a new
array of elements. In React, you use map() to generate lists of
components or HTML elements dynamically. React needs a unique key for
each item to track changes efficiently.
map_method.js:
import React from 'react';
return (
<div>
<h2>My Fruits:</h2>
{myList}
</div>
);
};
App.js:
import './App.css';
import {HelloWorld} from "./MyComponent/hello-world";
import {MapMethod} from "./MyComponent/map_method";
function App() {
return (
<div className="App">
<h1 className="text-center">Hello World</h1>
{HelloWorld()}
{MapMethod()}
<hello/>
</div>
);
}
export default App;
React Render HTML:
React's goal is in many ways to render HTML in a web page. React
renders HTML to the web page by using a function called createRoot()
and its method render().
App.js:
import './App.css';
function App() {
return (
<div className="App">
<h1 className="text-center">Hello World</h1>
</div>
);
}
export default App;
index.html:
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
JSX (JavaScript XML):
JSX (JavaScript XML) is a feature in React that allows you to write HTML-
like code directly within JavaScript. It makes it easier to create and
structure components by combining HTML and JavaScript in one place.
Instead of using complex JavaScript code to create elements, you can
write them in a format that looks like HTML, and React will convert it into
JavaScript behind the scenes.
1) Expressions in JSX - With JSX you can write expressions inside curly
braces { }. The expression can be a React variable, or property, or any
other valid JavaScript expression. JSX will execute the expression and
return the result:
const myElement = (
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Cherries</li>
</ul>
);
const myElement = (
<div>
<p>I am a paragraph.</p>
<p>I am a paragraph too.</p>
</div>
);
Alternatively, you can use a "fragment" to wrap multiple lines. This will
prevent unnecessarily adding extra nodes to the DOM. A fragment
looks like an empty HTML tag: <></>.
4) Elements Must be Closed - JSX follows XML rules, and therefore HTML
elements must be properly closed.
5) Attributes in JSX - JSX supports HTML like attributes. All HTML tags and
its attributes are supported. Attributes has to be specified using
camelCase convention (and it follows JavaScript DOM API) instead of
normal HTML attribute name. For example, class attribute in HTML has
to be defined as className. The following are few other examples:
Components are independent and reusable bits of code. They serve the
same purpose as JavaScript functions, but work in isolation and return
HTML. Components come in two types, Class components and Function
components, in this tutorial we will concentrate on Function components.
1) Class Component - A class component must include the extends
React.Component statement. This statement creates an inheritance to
React.Component, and gives your component access to
React.Component's functions. The component also requires a render()
method, this method returns HTML.
function Bike() {
return <h2>Hi, I am a Bike!</h2>;
}
function Cycle(props) {
return <h2>I am a {props.color} Cycle!</h2>;
}
function Airplane() {
return <h2>I am a Airplane and I live in Garage!</h2>;
}
function Garage() {
return (
<>
<h1>Who lives in my Garage?</h1>
<Airplane />
</>
);
}
<div>
<Cycle color='Blue'/>
</div>
);
}
export default App;
Props Component:
Props are arguments passed into React components. Props are passed to
components via HTML attributes. props stands for properties. React
Props are like function arguments in JavaScript and attributes in HTML. To
send props into a component, use the same syntax as HTML attributes:
Cycle.js:
export function Cycle(props) {
return <h2>I am a {props.color} Cycle!</h2>;
}
App.js:
import './App.css';
import {Cycle} from "./MyComponent/component";
function App() {
return (
<div>
<Cycle color='Blue'/>
</div>
);
}
export default App;
Pass Data Using Props:
1) Using Variable - If you have a variable to send, and not a string as in the
example above, you just put the variable name inside curly brackets:
function Car(props) {
return <h2>I am a { props.brand }!</h2>;
}
function Garage() {
const carName = "Ford";
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand={ carName } />
</>
);
}
2) Using Object:
function Car(props) {
return <h2>I am a { props.brand.model }!</h2>;
}
function Garage() {
const carInfo = { name: "Ford", model: "Mustang" };
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand={ carInfo } />
</>
);
}
Prop Validation:
React community provides a special package, prop-types to address the
properties type mismatch problem. prop-types allows the properties of the
component to be specified with type through a custom setting (propTypes)
inside the component.
UserAge.propTypes = {
age: PropTypes.number.isRequired, // Ensures 'age' is a required number prop
};
ReactJS Styling:
There are different ways to apply css in ReactJS in which most
commonly used are follows:
1) Inline Styling - Inline Styling is one of the safest ways to style the React
component. It declares all the styles as JavaScript objects using DOM
based css properties and set it to the component through style attributes.
Since the inline CSS is written in a JavaScript object, properties with
hyphen separators, like background-color, must be written with camel
case syntax:
App.js:
import './App.css';
function App() {
return (
<div className="App">
<h1 className="text-center">Hello World</h1>
<p style={{ color: 'yellow', backgroundColor: 'purple'}}>Lorem ipsum dolor
sit amet consectetur adipisicing elit.
</p>
</div>
);
}
export default App;
2) JavaScript Object - You can also create an object with styling information,
and refer to it in the style attribute:
App.js:
import './App.css';
function App() {
const pstyle = {
backgroundColor: 'purple',
fontSize: '20px',
color: 'yellow',
};
return (
<div className="App">
<h1 style={pstyle}Hello World</h1>
</div>
);
}
export default App;
3) CSS Modules - Css Modules provides safest as well as easiest way to
define the style. It uses normal css stylesheet with normal syntax. While
importing the styles, CSS modules converts all the styles into locally
scoped styles so that the name conflicts will not happen. Let us change
our component to use CSS modules
Conditional Statement:
1) if Statement - The if statement allows you to choose which component
to show based on a condition. If the condition is true, one component is
rendered; if false, another component is shown. This is useful when you
need more complex logic before deciding what to display.
2) for Loop - You can use a for loop to create lists in React by manually
pushing elements into an array and then returning that array in JSX. This
approach is useful when you need more control over the loop execution.
3) while Loop - A while loop can also be used to generate lists, but it is less
common. Similar to the for loop, you need to push elements into an array
and return the array in JSX.
List.js:
import React from 'react';
function Car(props) {
return <li>I am a {props.brand}</li>;
}
Keys:
Keys help React identify which elements have changed, been added, or
removed. Each key should be unique among siblings to allow React to
efficiently update and render the list without re-rendering unchanged
elements.
EXAMPLE:
function Garage() {
const cars = [
{id: 1, brand: 'Ford'},
{id: 2, brand: 'BMW'},
{id: 3, brand: 'Audi'}
];
return (
<>
<h1>Who lives in my garage?</h1>
<ul>
{cars.map((car) => <Car key={car.id} brand={car.brand} />)}
</ul>
</>
);
}
State in ReactJS:
State in ReactJS is an object that holds a component's dynamic data and
controls how the component behaves. When the state changes, React
automatically updates and re-renders the component to show the latest
data. This helps create interactive user interfaces that respond to user
actions.
a) Creating State Object - Creating a state is essential to building dynamic
and interactive components. We can create a state object within the
constructor of the class component.
b) Updating State in React - In React, a State object can be updated using
setState() method. React may update multiple setState() updates in a
single go. Thus using the value of the current state may not always
generate the desired result.
c) Managing Complex State - In React class components, state can be more
than just primitive values like numbers or strings. You can manage
complex state objects or arrays, but you need to be careful when
updating them to avoid directly mutating the state
Syntax:
this.state = { objectName: { property1: value1, property2: value2 } };
this.setState((prevState) => ({ objectName: { ...prevState.objectName,
updatedProperty: newValue } }));
render() {
return (
<div>
<h1>
The current count is :{" "}
{this.state.count}
</h1>
<button onClick={this.increment}>
Increase
</button>
<button onClick={this.decrement}>
Decrease
</button>
</div>
);
}
}
Event in ReactJS:
Events are just some actions performed by a user to interact with any
application. They can be the smallest of actions, like hovering a mouse
pointer on an element that triggers a drop-down menu, resizing an
application window, or dragging and dropping elements to upload them etc.
Events in React are divided into three categories:
a) Mouse Events − onClick, onDrag, onDoubleClick
b) Keyboard Events − onKeyDown, onKeyPress, onKeyUp
c) Focus Events − onFocus, onBlur
Event Management:
1) Adding Events in React - In React, events are written in camelCase
format. For example, instead of onclick used in HTML, React uses onClick.
Event handlers in React are written inside curly braces {}.
Example Comparison:
In React: <button onClick={shoot}>Take the Shot!</button>
In HTML: <button onclick="shoot()">Take the Shot!</button>
return (
<button onClick={shoot}>Take the shot!</button>
);
}
return (
<button onClick={() => shoot("Six!")}>Take the shot!</button>
);
}
3) React Event Object - The React Event Object is a special object that React
creates when an event (like a click) happens. It wraps the native browser
event and gives it a consistent structure across all browsers. It helps React
work the same way on different browsers. It gives you extra information
about the event, like:
a) event.target – The element that triggered the event.
b) event.type – The type of event (e.g., "click").
c) event.preventDefault() – Stops the default action (like stopping a
form from submitting).
d) event.persist() - If you want to use the event data after the handler
finishes(like a setTimeout), you need to store it using
event.persist().
setTimeout(() => {
alert("Hurray, Won The Match! 🎉"); // `null` (because of pooling)
}, 3000);
event.persist();
}
return (
<button onClick={(event) => shoot(event)}>Take the shot!</button>
);
}
React Forms:
React forms allow users to interact with the webpage, similar to how forms
work in HTML. You can create forms in React using the <form> element,
<input> fields, <textarea>, <select>, and other form components.
1) Adding Forms in React - Forms in React are added like any other HTML
element. However, in React, forms are usually controlled by the state
rather than letting the browser handle the data. This gives more control
over user input and how the form behaves.
2) Handling Forms - In HTML, the DOM usually handles form data directly.
However, in React, form data is managed through the component’s state.
This allows you to control the data and update the state in response to
user input using the onChange event handler.
3) Using useState to Manage Form State - React's useState hook is used to
manage form data. When an input changes, you can update the state
using setState or setName. This creates a "single source of truth" where
the input value reflects the state value.
4) Submitting Forms - You can prevent the default form submission (which
reloads the page) using event.preventDefault() inside an onSubmit
handler. This allows you to handle the form submission manually, such as
validating the data or sending it to a server.
5) Handling Multiple Input Fields - To handle multiple inputs in one state
object, you can use the name attribute to identify the input field. You can
then update the state dynamically using [event.target.name] to set the
value of the corresponding field in the state object.
EXAMPLE:
import React, { useState } from 'react';
import './Component.css';
// Simple validation
if (!formData.name || !formData.amount || !formData.date ||
!formData.category) {
alert('Please fill out all fields!');
return;
}
};
return (
<div id="expenseForm">
<form onSubmit={handleSubmit}>
<label htmlFor="name">Title</label>
<input
type="text"
id="name"
name="name"
placeholder="Enter expense title"
value={formData.name}
onChange={handleChange}
/>
<label htmlFor="amount">Amount</label>
<input
type="number"
id="amount"
name="amount"
placeholder="Enter expense amount"
value={formData.amount}
onChange={handleChange}
/>
React Animation:
https://www.tutorialspoint.com/reactjs/reactjs_animation.htm
React Router in Web Applications:
1) UseState hook - The useState hook in React lets you create and
manage data (state) in a function component. It allows your
component to remember values (like user input or a counter) and
update them when needed.
We use useState because it makes it easy to update the component
automatically when the state changes, without needing complex class
components.
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(count - 1)}>Dicrement</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);}
2) useEffect hook - The useEffect hook in React lets you run code
at specific times, like when the component loads, updates, or
gets removed. We use useEffect to handle side effects, such as
fetching data, updating the DOM, or setting up timers, without
needing lifecycle methods from class components.
useEffect(() => {
alert('Component mounted');
}, []); // Empty array = Runs only once (on mount)
useEffect(() => {
const timer = setInterval(() => {
console.log('Running every second');
}, 1000);
a) val is the initial value to be set for the returned mutable object,
refObj.
b) refObj is the object returned by the hook.
return (
<div>
<br /><br /><input ref={inputRef} type="text" placeholder="Type
something..." />
<br /><br /><br /><button onClick={handleFocus}>Change Color</button>
</div>
);
}
Store value that does not change on re-render:
export function UseRefRerenderWithoutResetValue() {
const a = useRef(0);
const [count, setCount] = useState(0);
return (
<div>
<p>State Count: {count}</p>
<button onClick={handleClick}>Increment</button>
</div>
);
}
4) useContext - The useContext hook in React lets you access data (like
a theme or user info) from a central place without passing it down
through props. We use useContext to make it easier to share data
between components, avoiding "prop drilling" (passing props through
many layers).
Parent.jsx:
import React, { createContext } from 'react';
import { ChildA } from './Child_A'; // Import named export
// Create Contexts
const data = createContext();
const data1 = createContext();
return (
<data.Provider value={name}>
<data1.Provider value={gender}>
<ChildA />
</data1.Provider>
</data.Provider>
);
}
return (
<>
<h1>Hi my name is {FirstName} and my gender is {gender}</h1>
</>
);
}
Child_A.jsx:
import React from "react";
import { ChildB } from "./Child_B"; // Importing named export
function ChildA() {
return <ChildB />;
}
Child_B.jsx:
import React from "react";
import { ChildC } from "./Child_C"; // Importing named export
CustomeHook.jsx:
import React from 'react';
import {useCounter} from './CustomCounter';
return (
<div>
<h1>Count: {count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
<button onClick={reset}>Reset</button>
</div>
);
}
CustomeCounter.jsx:
import { useState } from 'react';
Index.js:
import React from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux';
import {store} from './Store';
import App from './App';
App.js
import './App.css'
import Navbar from './Components/Navbar'
import { useSelector, useDispatch } from 'react-redux'
import { decrement, increment, multiply } from './Counter/counterSlice'
function App() {
const count = useSelector((state) => state.counter.value)
const dispatch = useDispatch()
return (
<>
<Navbar />
<div>
<button onClick={() => dispatch(decrement())}>-</button>
Currently count is {count}
<button onClick={() => dispatch(increment())}>+</button>
<button onClick={() => dispatch(multiply())}>*</button>
</div>
</>
)
}
navBar.js
import React from 'react'
import { useSelector} from 'react-redux'
return (
<div>
I am a navbar and counter is {count}
</div>
)
}
counterSlice.jsx
import { createSlice } from '@reduxjs/toolkit'
const initialState = {
value: 0,
}
Introduction to GraphQL:
GraphQL is a query language for APIs that allows clients to request
exactly the data they need, and nothing more. Unlike REST, where you
often get too much or too little data from fixed endpoints.
It works by defining a schema (like a blueprint) that describes the data
and how to access it. This makes it faster and more efficient because you
can combine multiple data requests into one query, reducing network
calls and improving performance. It's popular for building modern,
responsive web and mobile apps.
GraphQL Architecture:
3) Query Type - A query type is used to fetch data from the server. It
defines how a client can request specific information. Instead of
getting all the data, the client can ask for only the fields it needs,
making data retrieval more efficient.
4) Mutation Type - A mutation type is used to modify data on the server,
such as adding, updating, or deleting records. It works like POST, PUT,
or DELETE in REST APIs, allowing the client to send data to the server
and receive a response.
5) Enum Type - An enum type defines a fixed list of possible values for a
field. It’s useful when you want to restrict the values to specific
options, like days of the week or user roles. This ensures that only
valid values are used.
6) List Type - A list type allows a field to return multiple values of the
same type. Instead of getting just one result, you can get an array of
items, like a list of students or products. This makes it easy to handle
large sets of data.
a) Schema - The schema defines the structure of the data and the
operations allowed in GraphQL. It acts as a contract between the
client and the server, specifying what data can be requested and
how it is organized.
Parameter Description
This is a required argument. It represents a GraphQL
typeDefs
query as a UTF-8 string.
This is an optional argument (empty object by
Resolvers
default). This has functions that handle the query.
This is an optional argument and can be used to
logger
print errors to the server console.
This is an optional argument and allows
parseOptions customization of parse when specifying typeDefs as
a string.
This is true by default. When set to false, causes your
allowUndefinedIn
resolve functions to throw errors if they return
Resolve
undefined.
resolverValidation This is an optional argument and accepts an object
Options with Boolean properties.
inheritResolvers This is an optional argument and accepts a Boolean
FromInterfaces argument to check resolvers object inheritance.
Syntax:
fetch data, mutations are used to change data and return the
updated result to the client.
"dependencies": {
"@apollo/server": "^4.11.3",
"axios": "^1.8.3",
"body-parser": "^1.20.3",
"cors": "^2.8.5",
"express": "^4.21.2",
"graphql": "^16.10.0"
}
typeDefs: `
type User {
id: ID!
name: String!
username: String!
email: String!
phone: String!
website: String!
}
type Todo {
id: ID!
title: String!
completed: Boolean
user: User
}
`,}
4) Step 4: Define Query - A GraphQL Query consists of fields that define
how the response would look like. The Query is sent to the GraphQL
server which returns the response in the required format. Now, add
the following code snippet in the index.js file in typeDefs:
type Query {
getTodos: [Todo]
getAllUsers: [User]
getUser(id: ID!): User
resolvers: {
Todo: {
user: (todo) => USERS.find((e) => e.id === todo.id),
},
Query: {
getTodos: () => TODOS,
getAllUsers: () => USERS,
getUser: async (parent, { id }) => USERS.find((e) => e.id === id),
},
},
app.use(bodyParser.json());
app.use(cors());
await server.start();
app.use("/graphql", expressMiddleware(server));
app.listen(3000, () => console.log("Serevr Started at PORT 3000"));
}
Index.js:
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { ApolloClient, InMemoryCache, ApolloProvider } from
"@apollo/client";
Database Management:
Introduction to Database:
Components of a Database
1) Data: Data is the actual information stored within the database. It
includes various types of information such as names, addresses,
product details, or transaction records. The quality and accuracy of this
data are crucial for the effective functioning of any application that
relies on it.
2) Database Management System (DBMS): A DBMS is the software that
enables users to interact with the database. It provides tools and
functionalities for creating, retrieving, updating, and deleting data.
Popular examples of DBMS include MySQL, PostgreSQL, Oracle, and
Microsoft SQL Server. The DBMS acts as a mediator between the user
and the database, ensuring data integrity and security.
3) Schema: The schema defines the structure of the database, outlining
how data is organized. It includes the design of tables, fields (columns),
data types, and relationships between different data entities. The
schema serves as a blueprint for the database, ensuring consistency
and clarity in how data is stored and accessed.
4) Queries: Queries are commands used to request specific data from the
database. They allow users to retrieve, manipulate, and analyze the
information stored within. SQL (Structured Query Language) is the most
commonly used language for writing queries, enabling user to perform
operations like filtering, sorting and joining data from different table.
Types of Databases:
1) Relational Databases: Relational databases store data in structured
tables composed of rows and columns. Each table has a defined
schema, and relationships between tables are established using foreign
keys, allowing for complex queries and data integrity. They use SQL
(Structured Query Language) for data manipulation. Examples: MySQL,
PostgreSQL.
2) NoSQL Databases: NoSQL databases are designed to handle
unstructured or semi-structured data, offering flexibility in storing
various data types and structures. They are particularly useful for big
data applications, as they can efficiently manage large volumes of data.
NoSQL databases often prioritize scalability and performance over strict
consistency. Examples: MongoDB, Cassandra.
3) Object-Oriented Databases: Object-oriented databases store data as
objects, similar to the way programming languages like Java or C++
manage data. This model allows for complex data representations and
relationships, making it easier to work with data in applications that
require object-oriented programming principles. Object-oriented
databases are less common but can be beneficial in certain specialized
applications. Examples: db4o, ObjectDB.
4) Hierarchical Databases: Hierarchical databases organize data in a tree-
like structure, where records have parent-child relationships. Each
parent can have multiple children, but each child can only have one
parent. This structure is simple and efficient for certain types of data
relationships but can be inflexible for complex queries. Example: IBM
Information Management System (IMS).
5) Network Databases: Network databases improve upon hierarchical
databases by allowing multiple relationships between records, forming
a graph structure. This flexibility enables more complex relationships
and connections, making it suitable for applications where data
interconnections are vital. Examples: Integrated Data Store (IDS),
TurboIMAGE.
SQL, tor Sructured Query Language or Relational Database:
a) CREATE: to create a database and its objects like (table, index, views,
store procedure, function, and triggers)
b) ALTER: alters the structure of the existing database
c) DROP: delete objects from the database
d) TRUNCATE: remove all records from a table, including all spaces
allocated for the records are removed
e) COMMENT: add comments to the data dictionary
f) RENAME: rename an object
2) Data Manipulation Language (DML): DML is the short name for Data
Manipulation Language which deals with data manipulation and
includes most common SQL statements such SELECT, INSERT, UPDATE,
DELETE, etc., and it is used to store, modify, retrieve, delete and update
data in a database. Data query language(DQL) is the subset of “Data
Manipulation Language”. The most common command of DQL
is SELECT statement. SELECT statement help on retrieving the data from
the table without changing anything in the table.
3) Data Control Language (DCL): DCL is short for Data Control Language
which acts as an access specifier to the database.(basically to grant and
revoke permissions to users in the database
Step1: At the first step you have to download MySQL database and My
SQL workbench in your system by visiting MySQL web page:
https://www.mysql.com/downloads/.
Step4: After completion of all the above step now you are ready to
connect your database using sequelize as:
// db.js
const { Sequelize } = require('sequelize');
module.exports = sequelize;
Step5: You can check that connection is established or not by writing this
code in you index.js file:
// index.js
const express = require('express');
const sequelize = require('./db');
2) Create Database: Sequelize does not provide any way to create database
we have to create it manually using create databse <database name>
query on your sql workbench or command prompt.
module.exports = Student;
rollNo: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true, // Set rollNo as the primary key
},
b) After creating table:
4) Insert: Insert query is used to insert values in the table. We can insert
value in table by two ways:
})
5) Select From: Select from query is used to select the fields from the table.
Three many different way to select the field of table in which some of
are follows:
.then(() => {
// Select only name and class columns
return Student.findAll({
attributes: ['name', 'class']
});
})
.then(() => {
// Fetch all students
return Student.findAll();
})
.then(students => {
console.log("All Students:");
students.forEach(student => console.log(student.toJSON()));
})
.catch(err => {
console.error('Error:', err);
});
6) Where Clause: In MySQL, the WHERE clause can be used in SELECT,
DELETE and UPDATE queries. The WHERE clause allows you to specify a
search condition for the rows returned by a query.
Operator Description
.eq Equal
.gt Greater than
.lt Less than
.gte Greater than or equal
.lte Less than or equal
.ne Not equal
.or Logical or
.like Search for a pattern
.and Logical and
Example:
.then(() => {
// 🎯 Students NOT in class 10C
return Student.findAll({attributes: ['name', 'class'],where: {class:
{[Op.ne]: '10C'}}});
})
.then(students => {
console.log("Students NOT in class 10C:");
students.forEach(student => console.log(student.toJSON()));
})
7) Order By: Use the ORDER BY statement to sort the result in ascending or
descending order. The ORDER BY keyword sorts the result ascending by
default. To sort the result in descending order, use the DESC keyword.
Example:
Student.findAll({
attributes: ['rollNo', 'name', 'class'],
order: [['rollNo', 'DESC']]
})
8) Delete: DELETE query helps in removing one or more rows from a table.
Example:
Student.destroy({where: {rollNo: 2}})
.then(() => {
console.log('Student with rollNo 2 deleted');
})
.catch(err => {
console.error('Deletion error:', err);
});
9) Drop: By using you can delete the entire table as well as database:
Drop Table
Student.drop()
.then(() => console.log("� Student table dropped"))
.catch(err => console.error("❌ Drop error:", err));
Drop database:
Student.drop()
.then(() => console.log("� Student table dropped"))
.catch(err => console.error("❌ Drop error:", err));
10) Update: Table often needs to modify one or more records stored in a
MySQL database. This is done by passing the UPDATE query string as an
argument to the mysql.query() method.
Example:
Student.update(
{ class: '12B' }, // What to update
{ where: { rollNo: 1 } } // Condition
)
.then(() => {
console.log('📝 Student updated');
})
.catch(err => {
console.error('❌ Update error:', err);
});
11) Limit clause: LIMIT clause can be used with the select, update and
delete query restricts the all this operation to a specified number. For
example, LIMIT 5 deletes only first 5 records in the given order, select
limt 2 will select only two and same as update.
Example:
Student.findAll({
limit: 2
})
.then(students => {
console.log("📋 Limited students:");
students.forEach(student => console.log(student.toJSON()));
})
.catch(err => {
console.error("❌ Error:", err);
});
12) Join: A JOIN in SQL is used to combine rows from two or more tables,
based on a related column between them. There are different types of
JOINs in SQL, each serving a distinct purpose.
Types of Joins:
return StudentProfile;
};
// Setup associations
StudentModel.hasOne(StudentProfileModel, {foreignKey: 'rollNo', sourceKey:
'rollNo'});
StudentProfileModel.belongsTo(StudentModel, {foreignKey: 'rollNo', targetKey:
'rollNo'});
Step 3: Locate the column in profile table you want to join with
student table (index.js):
// Find all students with associated profiles
return StudentModel.findAll({
include: [{
model: StudentProfileModel,
attributes: ['bio', 'hobbies']
}]
});
})
1) Create Database:
// Initialize Firebase
const app = initializeApp(firebaseConfig);
2) Connect with Database:
To connect with your database first ensure that database is created
successfully and configuration is done properly then you have to
write this code in index.js file:
const express = require('express');
const { db } = require('./firebase-config.js');
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
3) Create Collection:
Now next step is to create collection. As firebase does not store data
into tables in row and column rather it store in files which makes it
possible to store any kind of data. Also collection will be shown in
firebase database when you insert the first value. Here how you can
create collection:
const express = require('express');
const { db } = require('./firebase-config');
const { collection, addDoc } = require('firebase/firestore');
app.use(express.json());
}
});
app.listen(PORT, () => {
console.log(`🚀 Server running at http://localhost:${PORT}`);
});
4) Insert values:
We can insert value by integrate frontend which we going to study in
next part here we work with backend only so there is two approach
to insert by sending post request through url or postman or insert
value directly:
a) Using Postman:
b) Insert directly:
Insert One:
// Function to directly insert a student
async function insertStudent(rollNo, name, email) {
try {
// Add document to Firestore
const docRef = await addDoc(collection(db, 'Students'), {
rollNo,
name,
email,
});
// Example usage
insertStudent('201', 'John Doe', '[email protected]');
Insert Multiple:
// Function to insert multiple students
async function insertMultipleStudents(students) {
try {
for (const student of students) {
const { rollNo, name, email } = student;
insertMultipleStudents(studentList);
5) Fetch Data from Database:
You can fetch data from firebase as follows:
querySnapshot.forEach((doc) => {
console.log(` ${doc.id}:`, doc.data());
});
} catch (err) {
console.error('Error fetching students:', err.message);
}
}
getAllStudents();
6)Where Clause:
const { getDocs, query, where } = require('firebase/firestore');
querySnapshot.forEach((doc) => {
console.log(`${doc.id}:`, doc.data());
});
} catch (err) {
console.error('Error fetching students:', err.message);
}
}
getStudents();
Operator Description Example
== Checks if the field equals the specified value. where('age', '==', 25)
Checks if the field is greater than the specified
> where('age', '>', 18)
value.
< Checks if the field is less than the specified value. where('age', '<', 30)
Checks if the field is greater than or equal to the
>= where('age', '>=', 18)
specified value.
Checks if the field is less than or equal to the
<= where('age', '<=', 30)
specified value.
Checks if the field value is one of the specified where('age', 'in', [25, 30,
in
values (array of values). 35])
Checks if the field value is not one of the where('age', 'not-in',
not-in
specified values. [25, 30])
(Currently unsupported in Firestore). Firestore
does not support "not equal to" queries. You can Not supported directly
!=
workaround this by using in with all values in Firestore.
except the ones you want to exclude.
7) Limit Clause:
The limit clause in Firestore allows you to restrict the number of
documents returned by a query. It's useful when you only need a
subset of the documents, rather than all the documents in a
collection.
// Fetch the first 3 students
const q = query(collection(db, 'Students'), limit(3));
// Example usage:
const newDetails = {
name: 'John Doe Updated',
email: '[email protected]',
};
updateStudentDetails('201', newDetails);
9) Delete data:
If you want to delete data (i.e., delete specific documents or fields)
from a Firestore collection, you can use the deleteDoc() function to
delete a document or updateDoc() to delete specific fields from a
document.
a) Delete a Specific Document: To delete an entire document from a
collection, use the deleteDoc() method. This will remove the
document and all its data from the Firestore database.
const { deleteDoc, doc } = require('firebase/firestore');
// Example usage:
deleteStudent('201');
b) Delete Specific Fields in a Document: If you only want to delete
specific fields from a document (instead of deleting the entire
document), you can use the updateDoc() method with
FieldValue.delete() to remove a field.
const { updateDoc, doc, deleteField } = require('firebase/firestore');
// Example usage:
deleteStudentFields('201');
Integrating Frontend:
React app:
It handles the user interface of the website first of all we have to
setup our react app which involves the create react app and
installing required packages:
Now main part begin is writing the actual code below code is belong to
app.js:
Step 1: Import require module -
import { useEffect, useState } from "react";
import axios from "axios";
import "./App.css"; // Make sure your styles are imported
useEffect(() => {
fetchUsers();
}, []);
Step 3: Handle the user Input –
const handleSubmit = async (e) => {
e.preventDefault();
try {
await axios.post(API_URL, form);
setForm({ name: "", email: "", rollNo: "" });
fetchUsers();
} catch (error) {
console.error("Submit error:", error.message);
}
};
<form onSubmit={handleSubmit}>
<input
value={form.rollNo}
onChange={(e) => setForm({ ...form, rollNo: e.target.value })}
placeholder="Roll No"
required
/>
<input
value={form.name}
onChange={(e) => setForm({ ...form, name: e.target.value })}
placeholder="Name"
required
/>
<input
value={form.email}
onChange={(e) => setForm({ ...form, email: e.target.value })}
placeholder="Email"
required
/>
<button type="submit">Add User</button>
</form>
<ul className="user-list">
{users.map((user) => (
<li key={user.id} className="user-item">
<span>
{user.name} ({user.email}) - Roll No: {user.rollNo}
</span>
<div className="user-actions">
<button className="edit" onClick={() =>
handleUpdate(user.id)}>Edit</button>
<button className="delete" onClick={() =>
handleDelete(user.id)}>Delete</button>
</div>
</li>
))}
</ul>
</div>
);
}
Now if you required you can also add css below code is belong to app.css
file:
.container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
h1 {
text-align: center;
}
.error {
color: red;
text-align: center;
}
form {
display: flex;
flex-direction: column;
gap: 10px;
margin-bottom: 20px;
}
input {
padding: 8px;
font-size: 16px;
}
button {
padding: 8px;
cursor: pointer;
background-color: rgb(48, 171, 74);
color: white;
border: none;
border-radius: 4px;
}
button:hover {
background-color: #0056b3;
}
.edit {
background-color: #28a745;
}
.edit:hover {
background-color: #218838;
}
.delete {
background-color: #dc3545;
}
.delete:hover {
background-color: #c82333;
}
.user-list {
list-style: none;
padding: 0;
}
.user-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
border-bottom: 1px solid #ddd;
}
.user-actions {
display: flex;
gap: 10px;
}
div{
background-color: #007bff;
}
Backend Building:
Server.js:
It is responsible for backend working as it is responsible for start and
handle the backend server and also work as an gateway for backend:
const express = require("express");
const cors = require("cors");
const dotenv = require("dotenv");
const sequelize = require("./db");
const userRoutes = require("./user-routes");
dotenv.config();
const app = express();
app.use(cors());
app.use(express.json());
app.use("/api/users", userRoutes);
sequelize.sync().then(() => {
app.listen(process.env.PORT, () =>
console.log(`Server started on port ${process.env.PORT}`)
);
});
db.js:
It is responsible for connected backend to the database weather it is
structure database or non structure database:
const { Sequelize } = require("sequelize");
module.exports = sequelize;
user.js:
As we use MySQL database which have the schema structure so user.js
creates the schema of our table:
const { DataTypes } = require("sequelize");
const sequelize = require("./db");
module.exports = User;
User-routes.js:
At least express is used to handle the CRUD operation using route
module:
const express = require("express");
const User = require("./user");
const router = express.Router();
// CREATE
router.post("/", async (req, res) => {
try {
const user = await User.create(req.body);
res.json(user);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// READ ALL
router.get("/", async (req, res) => {
const users = await User.findAll();
res.json(users);
});
// UPDATE
router.put("/:id", async (req, res) => {
try {
const user = await User.findByPk(req.params.id);
if (!user) return res.status(404).send("User not found");
await user.update(req.body);
res.json(user);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// DELETE
router.delete("/:id", async (req, res) => {
try {
const result = await User.destroy({ where: { id: req.params.id } });
res.json({ deleted: result });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
module.exports = router;
UNIT 4
Performance Optimization:
Code splitting:
Code splitting is a technique used to break your application into smaller,
separate chunks of code that can be loaded independently - Instead of
sending one large JavaScript bundle to the browser, your app only loads the
code it needs at a given time.
Feature:
1) Faster Initial Load - By loading only the essential code required for the
first screen, code splitting reduces the initial download size, making the
app load faster for the user. This is especially helpful for users on slow
networks or mobile devices.
2) Reduces Bandwidth Waste - Users don’t download code for parts of the
app they may never visit, which saves data and speeds up loading on
slower connections. It leads to a leaner and more efficient delivery of
resources.
3) Improves Caching - When you update your app, only the changed chunks
need to be re-downloaded, allowing the rest of the app to stay cached in
the browser. This helps avoid unnecessary re-downloads and speeds up
repeat visits.
4) Smoother User Experience - With less code to parse and execute at once,
the browser performs better, resulting in a more responsive and snappy
experience. It reduces memory usage and JavaScript execution time.
5) Better Scalability - As your app grows, code splitting helps manage
complexity by keeping the size of each chunk under control, making the
app easier to maintain and extend. It keeps large codebases more modular
and maintainable.
6) Lazy Loading Support - Code splitting pairs perfectly with lazy loading,
allowing components or routes to be loaded only when they’re actually
needed, which further improves speed and efficiency. This makes the app
feel faster and more dynamic for the user.
Approach to implement Code Splitting:
1) Using Lazy Loading:
const LazyComponent =
React.lazy(() => import('./MyComponent/CodeSpllitingUsingLibraries'));
CodeSpllitingUsingLibraries.jsx:
// LazyComponent.js
import React from 'react';
function App() {
const [showChart, setShowChart] = useState(false);
return (
<div>
<h1>Dashboard</h1>
<button onClick={() => setShowChart(true)}>Load Chart</button>
{showChart && (
<Suspense fallback={<div>Loading Chart...</div>}>
<ChartWidget />
</Suspense>
)}
</div>
);
}
export default App;
UsingComponentBasedLazyLoading.jsx:
import React from 'react';
// Retrieve data
const cachedData = JSON.parse(localStorage.getItem('userData'));
const persistConfig = {
key: 'root',
storage,
};
function App() {
const { data, error } = useSWR('/api/user', fetcher);
Image Formats – Use the right format for the right purpose (JPEG,
PNG, SVG, WebP).
Compression Techniques – Use tools like TinyPNG or ImageMagick
to compress images.
Lazy Loading – Load images only when they are about to enter the
viewport.
Example:
import React from 'react';
import LazyLoad from 'react-lazyload';
Choosing the Right Video Format – Use efficient formats like MP4
and WebM.
Compression Techniques – Use HandBrake to reduce video size.
Lazy Loading – Load videos only when needed.
Example:
const TerserPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
optimization: {
minimize: true,
minimizer: [new TerserPlugin()],
},
plugins: [new MiniCssExtractPlugin()],
};
Performance Optimization:
CI/CD Pipelines:
CI/CD (Continuous Integration / Continuous Delivery / Deployment) is a
modern approach to software development that automates the process of
building, testing, and releasing software. It replaces the slow, manual
workflows of traditional development methods with faster, repeatable, and
more reliable pipelines that allow for quick and continuous improvements.
Benefits of CI/CD:
1) Faster Development Cycles - CI/CD enables developers to push changes
frequently, reducing the time between writing code and releasing it. This
leads to quicker delivery of features, bug fixes, and updates to users.
2) Early Bug Detection - Since code is tested automatically after each
change, issues are caught early in the development process. This reduces
the cost and effort needed to fix bugs later.
3) Better Code Quality - Automated testing, code reviews, and validation at
each stage ensure that only high-quality code makes it to production.
This helps build more stable and reliable applications.
4) Reduced Manual Work - CI/CD automates repetitive tasks like testing,
building, and deployment. This saves developer time and reduces human
error in the process.
5) Easier Rollbacks - With smaller, more frequent changes, it’s easier to
identify what went wrong and roll back specific builds without affecting
the entire system.
6) Improved Collaboration - CI/CD fosters a collaborative environment
where developers, testers, and operations teams work closely. By
integrating and testing code frequently, teams gain better visibility into
each other's changes, which improves communication and reduces
integration issues.
Challenges of CI/CD:
Installing Docker:
(Click here to learn more)
Benefit:
Think of it like a separate storage space that Docker can use to save
files—like databases, logs, or uploaded files—even after the container is
gone. Volumes are stored on your system, not inside the container, which
makes them great for persistent data and sharing data between
containers.
g) Restoring a Docker Volume from Backup - Once you have your data
backed up in a tarball file, you can use the below command to restore
it back to a Docker volume. Heres the example command to restore a
volume called my_volume from a backup file −
6) Docker Network:
Docker Network allows containers to communicate with each other and
with the outside world. It creates virtual networks so containers can talk
safely, just like apps on a regular network.
b) List Networks - If you want to list all the networks on your host, you
can use the docker network ls command. The output of this command
will be a list of all the networks along with their names and drivers.
1) Prometheus:
Prometheus is an open-source monitoring tool used to collect, store,
and query performance data (called metrics) from servers, applications,
and services.
It works by scraping (pulling) data from targets like servers, containers,
or apps at regular intervals. These targets expose their data in a specific
format (usually on a /metrics endpoint), and Prometheus fetches that
information and stores it in a time-series database.
1) Error Logs:
Error logs are dedicated to capturing problems or unexpected behavior
in applications and systems. They are particularly useful for identifying
why a process failed or diagnosing application errors.