0% found this document useful (0 votes)
19 views64 pages

Web Application 3rd Sem

The document is a set of lecture notes prepared for a Web and Application Development course, covering essential topics such as HTML, CSS, JavaScript, Git, GitHub, React, Node.js, and Express. Each module includes hands-on labs, formative assessments, and final projects aimed at building a portfolio. The notes also provide detailed explanations of HTML syntax, elements, and tags, alongside practical examples for learners to follow.

Uploaded by

lilysikka777
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)
19 views64 pages

Web Application 3rd Sem

The document is a set of lecture notes prepared for a Web and Application Development course, covering essential topics such as HTML, CSS, JavaScript, Git, GitHub, React, Node.js, and Express. Each module includes hands-on labs, formative assessments, and final projects aimed at building a portfolio. The notes also provide detailed explanations of HTML syntax, elements, and tags, alongside practical examples for learners to follow.

Uploaded by

lilysikka777
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

AMBAPUA BERHAMPUR-10, GANJAM, ODISHA

WEB AND APPLICATION DEVELOPMENT (PCAC2003)


LECTURE NOTES

Prepared By:
Mr. Santosh Kumar Pandit
Lecture of Dept. of Computer Science and Engineering
GCE Ambapua, Berhampur-10
Module 1: Introduction to Web Development with HTML, CSS, JavaScript [13 Hours]
This starter course is designed for individuals aiming to become Web Developers, offering an introduction to the roles of front-
end, back-end, and full-stack developers in development projects. It also familiarizes learners with the terminology and skills
essential for a web development career. The focus is given to the languages needed for website or application development with a
comprehensive understanding of HTML and CSS for creating the structure and style of websites. JavaScript is introduced to
enable dynamic page features like interactive forms, dynamic content modification, and sophisticated menu systems. On
completing this course, learners will be able to create a basic structure for a website, format and layout for web applications,
enhance websites with rich, interactive applications, increase user interactivity and experience, and provide their websites with a
unique appeal. Hands-on labs provide practical application opportunities, and a final portfolio-worthy project involves creating a
webpage to showcase the skills learned.
Sub-Topic
Introduction to Application Development
CSS Overview & HTML5 Elements
HTML Overview
JavaScript Programming for Web Applications
Formative Assessments:
4 graded quizzes and 1 Peer-review assignment.
Module 2: Getting Started with Git and GitHub [18 Hours]
This self-paced introductory course provides an in-depth understanding of Git and GitHub, essential tools for collaboration and
social coding in modern software engineering and DevOps culture. Starting with Git and GitHub fundamentals, it covers key Git
concepts such as branching and repositories, along with the use of Git commands. The course includes hands-on labs, augmenting
understanding of Git concepts including forking, cloning, and merging workflows, and fostering team productivity on GitHub. It
concludes with a final project that allows students to begin building their portfolio with a public/open-source GitHub project, thus
demonstrating their Git and GitHub skills and providing a valuable addition to their resume. All activities are browser-based,
negating any need for specialized software installation on the learner's computer.
Sub-Topic
Git and GitHub Fundamentals
Using Git Commands and Managing GitHub Projects
Cloning and Forking GitHub Projects
Formative Assessments:
2 graded quizzes and 1 Peer-review assignment.
Module 3: Developing Front-End Apps with React [14 Hours]
This course provides comprehensive instruction on React, a popular framework for web and front-end application development.
The curriculum includes building rich front-end applications with React and ES6, connecting React components using data and
state, and writing advanced React components using Hooks and Redux. Learners will gain access to the React web framework UI
library and learn to run rich React applications, modify their properties and states, and connect to an external server from a React
page. The course also introduces various testing tools to verify components without manual checking. Hands-on labs and a final
portfolio-worthy project form part of the course, demonstrating learners' acquired React skills. This course is beneficial for those
looking to further their IT career as front-end or full-stack developers. Prior knowledge of HTML, CSS, JavaScript, and
Git/GitHub is required.
Sub-Topic
Advanced React
Building Rich Front-End Applications with React and ES6
React Components
Introduction to TypeScript
Passing Data and States Between Components
Formative Assessments:
3 graded quizzes and 1 Peer-review assignment.
Module 4: Developing Back-End Apps with Node js and Express [12 Hours]
This course primarily focuses on [Link] and Express, two popular web technologies. [Link], the most commonly used server-
side technology, and Express, the most prevalent server-side web framework, are vital for developing modern web applications. In
this course, you will concentrate on crafting applications using asynchronous callbacks and promises, creating REST APIs, and
performing CRUD operations. You will also learn to implement authentication and session management. Ample hands-on labs
provide practical experience, and a final project allows you to demonstrate your [Link] skills and add to your portfolio. This
course equips you to thrive as a back-end or full-stack developer and is perfect for IT professionals aspiring for career
advancement, new graduates looking to refine their server-side skills, and those managing cloud-centric projects. Prerequisites
include knowledge of JavaScript and Git.
Sub-Topics
Introduction to Server-Side JavaScript
Asynchronous I/O with callback programming
Express Web Application Framework
Formative Assessments:
3 graded quizzes and 1 Peer-review assignment.
Module 1
Introduction to HTML-
HTML stands for Hyper Text Markup Language. It is a language of World Wide Web. It is a
standard text formatting language which is used to create and display pages on the Web. It makes the text
more interactive and dynamic. It can turn text into images, tables, and [Link] is the most used language
for developing the web pages.
HTML was created by Berners-Lee in late 1991 but "HTML 2.0" was the first standard HTML
specification which was published in 1995. HTML 4.01 was a major version of HTML and it was
published in late 1999. Now we are having HTML-5 version which is an extension to HTML 4.01, and this
version was published in 2012.
A Markup Language is a set of instructions often called TAGS which can be added to text files. HTML is only a
formatting language are not a programming language. The idea behind hypertext is that instead of reading text in a
right linear structure we can easily jump from one point to another [Link] is all about specifying the structure
and format of our webpage i.e, it is mainly used for describing the structure document.
HTML is platform independent i.e, for example if we can access internet, we can access WORLD WIDE WEB
(WWW) irrespective of client OS and OS of the web server are accessing. So, we can view one download HTML
files on www through browser.
Elements of a web document are labeled through the usage of HTML tags. It is the tags that describe the document.
Anything that is not a tag will be displayed in the document itself. HTML does not describe any page layout i.e, for
example, word for windows have different styles for headings, font size etc. But HTML doesn’t have all these. Based
on the Platforms, appearance of any element will change. The formatted text will appear differently on different
machines / Platforms. By separating the Structure of the document and appearance, a Program that reads and
Understands HTML can make formatting decision based on capabilities of individual Platform. Web Browsers are
best examples of HTML formatters.
Advantages of HTML:-
 A HTML document is small and hence easy to send over the net. It is small because it doesn’t include
format information.
 HTML documents are cross platform compatible and device independent. We need a HTML readable
browser to view them.

Hello World Program:


<!DOCTYPE html>
<html>
<body>
<h1>Hello World!</h1>
</body>
</html>
HTML syntax
HTML syntax dictates the rules for writing Hyper Text Markup Language documents, which structure
content on the web. The core components of HTML syntax are:
Elements and Tags:
 HTML documents are built using elements, which are defined by tags.
 Most elements have an opening tag (e.g., <p>) and a closing tag (e.g., </p>). The closing tag includes a
forward slash before the tag name.
 The content of the element is placed between the opening and closing tags (e.g., <p>This is a
paragraph.</p>).
 Some elements are "empty" or "void" elements and do not have a closing tag or content
(e.g., <img>, <br>, <hr>).
Attributes:
 Attributes provide additional information about an HTML element.
 They are placed within the opening tag of an element and consist of a name-value pair (e.g., <a
href="[Link]">).
 Attribute values are typically enclosed in double quotes.
Document Structure:
 Every HTML document begins with a <!DOCTYPE html> declaration, which specifies the document
type and version (HTML5 in this case).
 The entire document content is enclosed within the <html> element.
 The <html> element contains two main sections:
 The <head> section: Contains meta-information about the document
(e.g., <title>, <meta>, <link>, <style>, <script>). This content is generally not directly visible on the
web page.
 The <body> section: Contains all the visible content of the web page, such as headings, paragraphs,
images, links, etc.
Nesting:
 HTML elements can be nested within each other, but they must be correctly nested
(e.g., <div><p>Content</p></div> is correct, but <p><div>Content</p></div> is incorrect).
HTML Document Structure
<!DOCTYPE html>
<html>
<head>
header related tags
</head>

<body>
body related tags
</body>
</html>

HTML Tag

Tag Description

<!DOCTYPE...> This tag defines the document type and HTML version.
<html> This tag encloses the complete HTML document and mainly comprises of document
header which is represented by <head>...</head> and document body which is
represented by <body>...</body> tags.
<head> This tag represents the document's header which can keep other HTML tags like
<title>, <link> ,<style>,<meta>,<script>etc.
<title> The <title> tag is used inside the <head> tag to mention the document title.
<body> This tag represents the document's body which keeps other HTML tags like <h1>,
<div>, <p> etc.
<h1>to <h6> Any Description starts with a heading. You can use different sizes for your headings.
HTML also has six levels of headings, which use the elements <h1>, <h2>, <h3>,
<h4>, <h5>, and <h6>. <h1> tag is large size and <h6> is small size
<p> The <p> tag offers a way to structure your text into different paragraphs. Each
paragraph of text should go in between an opening <p> and a closing </p> tags.
<br/> Whenever you use the <br /> element, anything following it starts from the next line.
<hr/> Horizontal lines are used to visually break up sections of a document. The <hr/> tag
creates a line from the current position in the document to the right margin and breaks
the line accordingly.
<!--> HTML comments are placed in between <!-- ... --> tags. So any content placed with-in
<!-- ... --> tags will be treated as comment and will be completely ignored by the
browser.
<b> Anything that appears within <b>...</b> element, is displayed in bold.
<i> Anything that appears within <i>...</i> element is displayed in italicized.
<mark> Anything that appears with-in <mark>...</mark> element, is displayed as marked
with yellow ink.
<center> You can use <center> tag to put any content in the center of the page or any table cell.
<big> The content of the <big>...</big> element is displayed one font size larger than the
rest of the text surrounding
<small> The content of the <small>...</small> element is displayed one font size smaller than
the rest of the text surrounding
<sup> The content of a <sup>...</sup> element is written in superscript; the font size used is
the same size as the characters surrounding it but is displayed half a character's height
above the other characters.
<sub> The content of a <sub>...</sub> element is written in subscript; the font size used is
the same as the characters surrounding it, but is displayed half a character's height
beneath the other characters.
<blockquote> Text inside a <blockquote> element is usually indented from the left and right edges of
the surrounding text, and sometimes uses an italicized font.
<q> The <q>...</q> element is used when you want to add a double quote within a
sentence. / Short Quotations
<s>/<del> Anything that appears within <strike>...</strike> element is displayed with
strikethrough, which is a thin line through the text
<u>/<ins> Anything that appears within <u>...</u> element, is displayed with underline
<pre> Any text between the opening <pre> tag and the closing </pre> tag will preserve the
formatting of the source document
<em> Anything that appears within <em>...</em> element is displayed as emphasized text.
<spam> The <samp>...</samp> element indicates sample output from a program, and script
etc. Again, it is mainly used when documenting programming or coding concepts.
<font> Fonts play very important role in making a website more user friendly and increasing
content readability. Font face and color depends entirely on the computer and browser
that is being used to view your page but you can use HTML <font> tag to add style,
size, and color to the text on your website.
<iframe> You can define an inline frame with HTML tag <iframe>. The <iframe> tag is not
somehow related to <frameset> tag, instead, it can appear anywhere in your
document. The <iframe> tag defines a rectangular region within the document in
which the browser can display a separate document, including scrollbars and borders.
<marquee> An HTML marquee is a scrolling piece of text displayed either horizontally across or
vertically down your webpage depending on the settings. This is created by using
HTML <marquees> tag.
<caption> The <caption> tag in HTML is used to provide a title or brief description for
a <table> element.
<address> The <address>...</address> element is used to contain any address.
<kbd> When you are talking about computers, if you want to tell a reader to enter some text,
you can use the <kbd>...</kbd> element to indicate what should be typed
<div> The <div> and <span> elements allow you to group together several elements to
create sections or subsections of a page.
<span> The <div> and <span> elements allow you to group together several elements to
create sections or subsections of a page.
<header> The <header> tag in HTML is a semantic element used to define the introductory
content or navigational links for a document or a section within a document.
<nav> The <nav> tag is used in HTML to define a section of a webpage that contains
navigation links. Its primary purpose is to provide semantic meaning and improve the
accessibility and search engine optimization (SEO) of a website.
<section> The <section> tag in HTML is a semantic element used to define a generic
standalone section of a document. Its primary purpose is to provide a logical grouping
of related content within a webpage.
<footer> The <footer> tag in HTML is used to define the footer section of an HTML
document or a specific section within it. Its primary purpose is to semantically group
content that typically appears at the end of a page or a content block.
<picture> The <picture> tag in HTML is used to provide responsive images, allowing
developers to specify different image sources for various screen sizes, resolutions, and
other media conditions. This addresses the challenge of displaying images optimally
across a wide range of devices, from small mobile phones to large desktop monitors.
<map> The <map> tag in HTML is used to define a client-side image map. An image map is
an image with clickable areas, where different parts of the image can be linked to
different destinations or trigger specific actions.
<svg> The <svg> tag in HTML is used to embed Scalable Vector Graphics (SVG) directly
within an HTML document. SVG is an XML-based vector image format, meaning that
images are defined using mathematical descriptions of shapes, paths, and text, rather
than a grid of pixels.
&nbsp; Its use for word space

Example using all html basic tags


<!DOCTYPE html>
<html>
<head>
<title>assignment1</title>
</head>
<body>
<h1> <center>INDEPENDENCE DAY </center> </h1>
<p><b>After years of slavery and bondage under the British Empire, India got its independence in 1947. it was not an easy
task. it took a lot of selfless effort on the part of great pepole like Mahatma Gandhi, Jawaharlal Nehru, Subash Chandra Bose,
Bal Gangadhar Tilak Etc.</b></p>
<p><i>They had to make a lot of sacrifices for freedom from British rule because they loved the country and cared for the
people. they could not stand the sight of people being oppressed and tortured to work like slaves in their own land.
</i></p>
<h3>Short Article</h3>
<p><mark>The Independence Day reminds every Indian of the beginning of a new era, the start of a new life free from
bondage and slavery. it is for the same reason that independence day is given so much importance and celebrated in a very grand
manner across the country.
</mark></p>
<p> <big>The Indian Independence bill </big> which was a vital part of the journey to freedom, was passed by
<small>The British Parliament.</small>The 15<sup>th</sup> of August 1947 marked the end of British colonialism and the
dawn of the democratic <sub>re</sub>public.</p>
</body>
</html>
Html Lists:
Lists lets us display information in a compact, right format. There are three kinds of lists:
1. Unordered List(bullets)
2. Ordered List(numbers)
3. Definition List(dictionary)
Unordered List:
An Unordered list is a list of items that are marked with burden. The Unordered list is created
by using <ul>tag are the list items in the list are created by </ul>tag and the list items in the list are
created by <li> tag.
<ul>
<li>ListItem1</li>
<li>ListItem2</li>
</ul>
Example:
<html>
<head>
<title>Creating UnorderList</title>
</head>
<body bgcolor="pink">
<h1 align="center">CreatingUnorderList</h1>
<h1 align="center">ListofCollegesinBerhampur</h1>
<ul>
<li>GCE</li>
<li>GSE</li>
<li>GIST</li>
</ul>
</body>
</html>
Output

Creating Customized Unordered Lists:


We customized unordered lists by setting the “Type” attribute to three different values. DISC (default),
SQUARE and CIRCLE which sets the type of bullet that appears before the list item.
Example:
<html>
<head>
<title>Creating Unorder List</title>
</head>
<body bgcolor="pink">
<h1 align="center">Creating Unorder List</h1>
<h1 align="center">List of Colleges in Berhampur</h1>
<ultype="square">
<li>GCE</li>
<li>GIST</li>
<li>GSE</li>
</ul>
</body>
</html>
Output
Ordered List:
While the unordered lists display simple bullet before each list item. Ordered lists use a number
system/lettering scheme to indicate that the items are ordered in some ways, ordered lists are created by
<ol> tag and the list items are created using <li>tag.
Example:
<html>
<head>
<title>Creating Order List</title>
</head>
<body bgcolor="pink">
<h1 align="center">Creating Order List</h1>
<h1 align="center">List of branches in GCE</h1>
<ol>
<li>CSE</li>
<li>AI</li>
<li>EEE</li>
<li>CIVIL</li>
<li>ME</li>
</ol>
</body>
</html>
Output

Creating Customized Ordered Lists:-


We can customize the numbering system used in ordered lists by using the TYPE attribute, which we
can set to these values:
1. Default numbering system (1,2,3,….)
A. Upper case Letters(A,B,C, …..)
a. Lower case Letters(a,b,c,…)
I. Large Roman Numerals (I,II,III,….)
i. Small Roman Numerals (i,ii,iii,…..)
Example:
<html>
<head>
<title>Creating Order List</title>
</head>
<body bgcolor="pink">
<h1 align="center">Creating Order List</h1>
<h1 align="center">List of branches in GCE</h1>
<ol type="A">
<li>CSE</li>
<li>AI</li>
<li>EEE</li>
<li>CIVIL</li>
<li>ME</li>
</ol>
</body>
</html>
Output

Definition List:-
These lists include both definition terms as well as their definition. To create the definition lists we
use <dl> tag. For creating definition terms we use <dt> tag and for data definitions we use <dd>tag.
Example:
<html>
<head>
<title>Creating Definition List</title>
</head>
<body bgcolor="pink">
<h1 align="center">Definition List</h1>
<dl>
<dt>CSE</dt><dd>Computer Science & Engineering</dd>
<dt>ME</dt><dd>Mechanical Engineering</dd>
<dt>AI</dt><dd>Artificial Intelligence</dd>
<dt>EEE</dt><dd>Electrical & Electronics Engineering</dd>
<dt>CE</dt><dd>Civil Engineering</dd>
</dl>
</body>
</html>
Output

Attributes-:
<tag name att name=”value”>……</tag name>
1) Align
Left , right , center
2) Direction
Ltr , Rtl
HTML Color coding system-Color Names
There are 3 different methods to set color.
o We can set color using three methods.
a. Using color name
<body bgcolor=”red”>
<font color=”red”>
b. Using RGB(Red, Green, Blue)value abs (0to255) & %(0to100)
<body bgcolor=”rgb(72,0,0)”>
<font color=”rgb(72,0,0)”>
<body bgcolor=”rgb(72%,0%,0%)”>

c. Using Hexa decimal value


<body bgcolor=”#ffff00”>
<font color=”#ffff00”>

HTML-Hypertext Reference (href) or Hyperlinks


o The href attribute defines reference that the link refers to. Basically this is where the user will be taken if
they wish to click this link.
o Use the <a></a> tags to define the start and ending of an anchor.
o Decide what type of href attribute you need and place this attribute into the opening tag.
o The text you place between the opening and closing tags will be shown as the link on a page. Use the
demonstration below as a reference.
<a href="[Link]

HTML– Images
o Use the <img/> tag to place an image on your webpage.

<imgsrc="[Link]"/>
Image src
o Above we have defined the src attribute.
o Src stands for source, the source of the image or more appropriately, where the picture file is
located.
o There are two ways to define the source of an image. First you may use a standard URL.
(src=[Link] As your second choice, you may copy or upload
the file onto your web server and access it locally using standard directory tree methods.
(src="../[Link]")
o The location of this picture file is in relation to your location of [Link] file.
HTML Comments
Comment is a piece of code which is ignored by any web browser. It is a good practice to
add comments into your HTML code, especially in complex documents, to indicate sections of a
document, and any other notes to anyone looking at the code. Comments help you and others
understand your code and increases code readability.
HTML comments are placed in between <!-- ... --> tags. So any content placed with-in <!-- ... -->
tags will be treated as comment and will be completely ignored by the browser.
HTML Iframes
You can define an inline frame with HTML tag <iframe>. The <iframe> tag is not somehow
related to <frameset> tag, instead, it can appear anywhere in your document. The <iframe> tag
defines a rectangular region within the document in which the browser can display a separate
document, including scrollbars and borders.
The src attribute is used to specify the URL of the document that occupies the inline frame.
<iframe src="/html/[Link]">
your browser is support inline frames.
</iframe>
HTML Marquees
An HTML marquee is a scrolling piece of text displayed either horizontally across or vertically
down your webpage depending on the settings. This is created by using HTML <marquees> tag.
<marquee>
One or more lines or text message or image
</marquee>

HTML TABLE
An HTML table is a structured way to display data in rows and columns on a web page. It is
created using the <table> element and its associated elements for defining rows, header cells, and data
cells.
A HTML table arranges data/information in terms of rows and columns. Tables are defined in HTML
using <table> tag. A table is divided into rows and each row each divided into data cells (columns). The
rows of table are created using <tr> tag and data cells are created by <td> tag.
<tr>-Table row
<td>-Table data
Key HTML elements for creating a table:
 <table>: The main container for the entire table.
 <tr>: Defines a table row. Each <tr> element represents a new row in the table.
 <th>: Defines a table header cell. These cells typically contain headings for the columns and are often
displayed in bold by default.
 <td>: Defines a standard table data cell. These cells contain the actual data within the table.
Optional elements for enhanced structure:
 <thead>: Groups the header content in a table.
 <tbody>: Groups the body content in a table.
 <tfoot>: Groups the footer content in a table.
 <caption>: Provides a short description or title for the table.
Example
<table>
<caption>Monthly Sales Data</caption>
<thead>
<tr>
<th>Month</th>
<th>Product A Sales</th>
<th>Product B Sales</th>
</tr>
</thead>
<tbody>
<tr>
<td>January</td>
<td>150</td>
<td>200</td>
</tr>
<tr>
<td>February</td>
<td>180</td>
<td>220</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3">Total sales data for the first two months.</td>
</tr>
</tfoot>
</table>
Attributes of <table> tag:
 align: specifies the horizontal alignment of the table in the browser window, set to ”left, center,
right”.
 background: specifies the URL of a background image to be used as background for the table.
 bgcolor: sets the background color of the table cells.
 border: sets the border width.
 bordercolor: sets the external border color of the entire table.
 cellpadding: sets the spacing between cell walls and content.
 cellspacing: sets the spacing between table cells.
 height: sets the height of the whole table.
 width: sets the width of the table.

Attributes of <tr> tag:


 align: specifies the horizontal alignment content in the table cells set to “left,center,right”.
 bgcolor: sets the background color of the table cells.
 bordercolor: sets the external border color of the entire table.
 Valign: sets the vertical alignment of data, set to top, middle, bottom.
Alignmentof<td>tag
 align: specifies the horizontal alignment content in the table cells set to “left, center, right”.
 bgcolor: sets the background color of the table cells.
 bordercolor: sets the external border color of the entire table.
 colspan: indicates the how many cell columns of the table this cell should span.
 rowspan: indicates the how many cell rows of the table this cell should span.
Example/Assignment-:
<!DOCTYPE html>
<html>
<head>
<title>assignment1</title>
</head>
<body>
<table bgcolor="red" , width="100%", height="100px">
<thead>
<tbody>
<tr>
<td align="left"> Ph-: +91 7978685395 </td>
<td align="right"> email-: Panditsantosh666@[Link] </td>
</tr>
</tbody>
</thead>
</table>
<img src="[Link]" width="100%", height="300px",/>
<marquee bgcolor="yellow",width="100%",height="100px", scrollamount="3",behavior="slide">
Name-: [Link] Kumar Pandit, Ph-:+91 7978685395,
</marquee>
<h1 align="center">web development</h1>
<p><blockquote style="color:#00ff00 ;">web development is the work involved in developing a
website for the internet.
web development can range from developing a simple single static page of plain text to
complex web applications, electronic businesses,and social network services.
</blockquote></p>
<h3 align="left">Courses</h3>
<table>
<thead>
<tbody>
<tr>
<td><img src="[Link]" width="50%",height="25"/></td>
<td><img src="[Link]" width="50%",height="25"/></td>
<td><img src="[Link]" width="50%",height="25"/></td>
<td><img src="[Link]" width="50%",height="25"/></td>
</tr>
<tr>
<td align="center">html</td>
<td align="center">reactjs</td>
<td align="center">nordjs</td>
<td align="center">java</td>
</tr>
</tbody>
</thead>
</table>
<table>
<thead>
<tbody>
<td> <iframe
src="[Link]
421642!3d19.310291349585654!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x3a3d507a2780
7e73%3A0x926af4855889db12!2sGoilundi%2C%20Brahmapur%2C%20Odisha%20760004!5e0!3m2!1sen
!2sin!4v1660153678183!5m2!1sen!2sin" width="600" height="450" style="border:0;" allowfullscreen=""
loading="lazy" referrerpolicy="no-referrer-when-downgrade" width="50%"
height="200px"></iframe>"</td>
<td> <iframe width="727" height="409"
src="[Link] title="How to Start Web Development? Complete
Roadmap for FullStack Developer | 2022" frameborder="0" allow="accelerometer; autoplay; clipboard-
write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen width="50%"
height="200px"></iframe>"</td>
</tbody>
</thead>
</table>
<h4>Courses details</h4>
<ul type="circle">
<li>html</li>
<li>reactjs</li>
<li>nordjs</li>
<li>java</li>
</ul>
<ol type="i">
<li>html</li>
<li>reactjs</li>
<li>nordjs</li>
<li>java</li>
</ol>
<dl>
<dt>html</dt>
<dd>HTML stands for Hyper Text Markup Language. HTML is the standard markup
language for Web pages. HTML elements are the building blocks of HTML pages.</dd>
<dt>reactjs</dt>
<dd>React (also known as [Link] or ReactJS) is a free and open-source front-end JavaScript
library for building user interfaces based on UI components.</dd>
<dt>nordjs</dt>
<dd>[Link] is an open-source, cross-platform, back-end JavaScript runtime environment that
runs on the V8 engine and executes JavaScript code outside a web browser, which was designed to build
scalable network applications.</dd>
<dt>java</dt>
<dd>Java is a high-level, class-based, object-oriented programming language that is designed
to have as few implementation dependencies as possible.</dd>
</dl>
<marquee>
<img src="[Link]" width="100%" height="300px"/>
<img src="[Link]" width="100%" height="300px"/>
<img src="[Link]" width="100%" height="300px"/>
<img src="[Link]" width="100%" height="300px"/>
</marquee>
</body>
</html>
HTML Forms
HTML Forms are required when you want to collect some data from the site visitor. For during
user registration you would like to collect information such as name, email address, credit card,
etc.
A form will take input from the site visitor and then will post it to a back-end application such as
ASP Script or PHP script etc. The back-end application will perform required processing on the
passed data based on defined business logic inside the application.
There are various form elements available like text fields, text area fields, drop-down menus,
radio buttons, checkboxes, etc.
The HTML <form> tag is used to create an HTML form and it has following syntax:
<formaction="Script URL"method="GET|POST">
form elements like input, textarea etc.
</form>
Form Attributes
Apart from common attributes, following is a list of the most frequently used form attributes:
Attribute Description
Action Backend script ready to process your passed data.
Method Method to be used to upload data. The most frequently used are GET
and POST methods.

HTML Form Controls


There are different types of form controls that you can use to collect data using
HTML form:
• Text Input Controls
• Checkboxes Controls
• Radio Box Controls
• Select Box Controls
• File Select boxes
• Hidden Controls
• Clickable Buttons
• Submit and Reset Button
Example
<html>
<head>
<title> login form </title>
</head>
<body>
<table>
<div>

<h1><u> Login </u></h1>


<form>
<p><b>User Name </b></p>
<input type="text" name ="User Name" placeholder="Enter user name"/>
<p><b>DOB</b> </p>
<input type="date" date of birth=" "/>
<p><b>Gender</b></p>
<input type="radio" name="gender"/>male
<input type="radio" name="gender"/>female
<p><b>Address</b></p>
<input type="text" name="Address"placeholder="Enter Your Address"/>
<p><b>Mobile No</b></p>
<input type="Number" name="Mobile No"placeholder="Enter Your Mobile No"/>
<p><b>Password </b></p>
<input type="password" name = "password" placeholder=" Enter password"/>
<br/>
<br/>
<input type="submit" name ="Submit" value= "login"/>
<br/>
<a href = "#">Forget Password ?</a>
<br/>
<a href = "#">New User click here !! </a>

</form>
</div>
</table>
</body>
</html>
Introduction to CSS

CSS
Css stands for Cascading Style Sheets CSS describes how HTML elements are to be displayed on
screen, paper, or in other media. CSS saves a lot of work. It can control the layout of multiple web
pages all at once.
Style sheets represent the World Wide Web consortium's effort to improve on the tag and attribute based
style of formatting. Style sheets provide a way of customizing whole pages all at once and in much richer
detail than the simple use of tags and attributes. The format of style sheet will be:
<style type=”text/css”>
selector{property:value;property:value;}
selector{property:value;property:value;}
</style>
Every line in<style> tag is called as a „Rule‟ and a style rule has two parts:
a. Selector.
b. Set of declarations.
A selector is used to create a link between the rule and the HTML tag. The declaration has two parts
again:
a. Property.
b. Value.
A property specifies additional information and value specifies property value. For example:
<style type=”text/css”>
body{background-color:#d0e4fe;}
h1 {color:orange; text-align:center;}
p {font-family:"TimesNewRoman"; font-size: 20px;}
</style>
If we add above code in the <head> element of webpage, entire webpage will be displayed in various styles
given in style element.
CSS can be added to HTML elements in 3 ways:
 Inline- by using the style attribute in HTML elements
 Internal/Embedded -by using a <style>element in the <head>section
 External-by using an external CSS file
Inline Style Sheets:
Inline style sheets mix content with presentation. To use inline styles we use style attribute in the relevant
tag.
Example:
<!DOCTYPE html>
<html>
<head>
<title>HTML Tables</title>
</head>
<body bgcolor="pink">
<center>
<h1>Creating HTML Tables</h1><br/>
<table border="2"cellpadding="4"cellspacing="4">
<tr>
<th colspan="2"style="background-color:red">WebSites</th>
</tr>
<tr>
<th style="background-color:blue">MailSites</th>
<th style="background-color:green">JobSites</th>
</tr>
<tr>
<td style="background-color:grey">Gmail</td>
<td style="background-color:aqua">Naukri</td>
</tr>
<tr>
<td style="background-color:yellow">Yahoo</td>
<td style="background-color:purple">JobStreet</td>
</tr>
</table>
</center>
</body>
</html>

Output:

Embedded Style sheets:


An embedded style sheet is used when a single document has a unique style. We define internal
styles in the head section of a HTML page by using <style> tag. The styles defined using embedded style
sheets are applied throughout the page and we put the styles into one place.
Example:
<!DOCTYPE html>
<html>
<head>
<title>EmbeddedStylesheets</title>
<style type="text/css">
body{background-color: pink;}
h1 {color:orange;text-align: center;}
p {font-family:"Times New Roman";font-size:20px;}
</style>
</head>
<body>
<h1>EmbeddedStyle Sheets</h1><br/>
<p>Comment is a piece of code which is ignored by any web browser.
It is a good practice to add comments into your HTML code, especially in complex documents,
to indicate sections of a document, and any other notes to anyone looking at the code.
Comments help you and others understand your code and increases code readability.</p>
</body>
</html>
Output:
External Style Sheets:
External style sheets are just that the style sheets are stored separately from our webpage. These
are useful especially if we are setting the styles for an entire website. When we change the styles in
external style sheet we change the styles of all pages. We use <link> element to access the style sheet file
defined into our webpage. The format of <link> element is:
<link rel="stylesheet" href="[Link]">
Example:
[Link]

<!DOCTYPE html>
<html>
<head>
<title>ExternalStyle Sheets</title>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<h1 class="h1">External Style Sheets</h1><br/>
<p class="p">Comment is a piece of code which is ignored by any web browser.
It is a good practice to add comments into your HTML code, especially in complex documents,
to indicate sections of a document, and any other notes to anyone looking at the code.
Comments help you and others understand your code and increases code readability.</p>
</body>
</html>

[Link]
body {
background-color: aqua;
}
.h1 {
color:olive;
text-align: center;
font-size:32px;
}
.p {
font-family:"Times New Roman";
font-size:20px;
}
Output:

What is the difference between class and id?


The id Selector
 The id selector is used to specify style for a single, unique element.
 The id selector uses the id attribute of the HTML element, and is defined with a "#".
 The style rule below will be applied to the element with id ="para1":
#para1
{text-align:center; color:red;}
The class Selector
 The class selector is used to specify a style for a group of elements. Unlike the id selector, the class selector is
most often used on several elements.
 This allows you to set a particular style for many HTML elements with the same class.
 The class selector uses the HTML class attribute, and is defined with a "."
 In the all HTML elements with class ="center" :
.center{text-align:center;}
Explain CSS Background with all its attributes
 CSS background properties are used to define the background effects of an element.
1. CSS Background Color
o The background-color property specifies the background color of an element.
o The background color of a page is defined in the body selector:
body{background-color:#b0c4de;}

2. CSS Background Image


o The background-image property specifies an image to use as the background of an element.
body{background-image:url('[Link]');}
3. Background Image Repeat
o You can have a background image repeat vertically (y-axis), horizontally (x-axis), in both directions, or in
neither direction.
p{background-image:url([Link]);background-repeat:repeat;}
h4{background-image:url([Link]);background-repeat:repeat-y;}
ol {background-image: url([Link]); background-repeat: repeat-x; }
ul{background-image:url([Link]);background-repeat:no-repeat;}
Explain CSS Font with all its attributes
 CSS font properties define the font family, boldness, size, and the style of a text.
1. CSS Font Color
o Set the text-color for different elements:
h4{color:red;}
h5{color:#9000A1;}
h6{color:rgb(0,220,98);}
2. CSS Font Family
o The font family of a text is set with the font-family property.

h4{font-family:sans-serif;}
h5{font-family:serif;}
h6 { font-family: arial;}
3. CSS Font Size
o The font-size property sets the size of the text.
p{font-size:120%;}
ol{font-size:10px;}
ul{font-size:x-large;}
4. CSSFontStyle
o The font-style property is mostly used to specify italic text.
o This property has three values:
 normal-The text is shown normally
 italic-The text is shown in italics
 oblique-The text is "leaning" (oblique is very similar to italic, but less supported)
p{font-style:italic;}
h4{font-style:oblique;}
5. CSS Font Weight
o The font-weight property sets how thick or thin characters in text should be displayed.
p{font-weight:100;}
ul{font-weight:bolder;}
6. CSS Font Variant
o The font-variant property specifies whether or not a text should be displayed in a small-caps font.
p{font-variant:small-caps;}
Explain CSS Text with all its attributes.
 While CSS Font covers most of the traditional ways to format your text, CSS Text allows you to control the
spacing, decoration, and alignment of your text.
1. Text Decoration
o The text-decoration property is used to set or remove decorations from text.
o The text-decoration property is mostly used to remove underlines from links for design purposes.
h4{text-decoration:line-through;}
h5{ text-decoration: overline; }
h6{text-decoration:underline;}
a { text-decoration: none; }
2. Text Indent
o The text-indentation property is used to specify the indentation of the first line of a text.
p{text-indent:20px;}
h5{text-indent:30%;}
3. Text Align
o The text-align property is used to set the horizontal alignment of a text.
p { text-align: right; }
h5{text-align:justify;}
4. Text Transform
o The text-transform property is used to specify upper case and lower case letters in a text.
p{text-transform:capitalize;}
h5{text-transform:uppercase;}
5. CSS White Space
o The white-space attribute allows you to prevent text from wrapping until you place a break <br /> into your text.
p{white-space:nowrap;}
6. CSS Word Spacing
o With the CSS attribute word-spacing you are able to specify the exact value of the spacing between your words.
Word-spacing should be defined with exact values.
p{word-spacing:10px;}
7. CSS Letter Spacing
o With the CSS attribute letter-spacing you areable to specify the exact value of the spacing between your letters.
Letter-spacing should be defined with exact values.
p{letter-spacing:3px;}
Task-1
<!DOCTYPE html>
<html>
<head>
<title>assignment9</title>
<style>
.topbar
{
background-color: blue;
background-size: 100%;
height: 35px;
}
.ctopbar
{
width:50%;
float:left;
}
.right
{
float:right;
}
.nav
{
background-color: bisque;
width:100%;
height:130px;
}
.navimg
{
width:30%;
float:left;
}
.height
{
height:90px;
}
.navbar
{
width:70%;
float:left;
}
.img
{
width:100%;
height:450px;
}
.bd
{
background-color: burlywood;
width:100%;
height:170px;
}
.p,h1
{
text-align:center;
color: brown;
}
</style>
</head>
<body>
<div class="topbar">
<div class="ctopbar"><p>+91 7978685395</p></div>
<div class="ctopbar"><p class="right">panditsantosh666@[Link]</p></div>
</div>
<div class="nav">
<div class="navimg">
<img src="food corner [Link]" class="height"/>
</div>
<div class="navbar">
<div class="right">
<a href="[Link]">home</a>&nbsp;&nbsp;&nbsp;
<a href="[Link]">menu</a>&nbsp;&nbsp;&nbsp;
<a href="[Link]">add cart</a>&nbsp;&nbsp;&nbsp;
<a href="[Link]">about</a>&nbsp;&nbsp;&nbsp;
<a href="[Link]">contact</a>&nbsp;&nbsp;&nbsp;
</div>
</div>
</div>
<div class="img">
<img src="food [Link]" class="img"/>
</div>
<div class="bd">
<br/>
<h1 class="h1,p">welcome to food corner</h1>
<p class="h1,p"> &nbsp;&nbsp;your diet is a bank account.
<br/>
good food choices are good investments.
Food is any substance consumed to provide nutritional support for an organism.
Food is usually of plant, animal, or fungal origin, and contains essential nutrients,
such as carbohydrates, fats, proteins, vitamins, or minerals.
The substance is ingested by an organism and assimilated by
the organism's cells to provide energy, maintain life, or stimulate growth.
</p>
</div>
</body>
</html>
Explain BOX MODEL.
 All HTML elements can be considered as boxes. In CSS, the term "box model" is used when talking about
design and layout.
 The CSS box model is essentially a box that wraps around HTML elements, and it consists of: margins, borders,
padding, and the actual content.
 The box model allows us to place a border around elements and space elements in relation to other elements.
 The image below illustrates the box model

 Explanation of the different parts:


o Margin- Clears an area around the border. The margin does not have a background color, it is completely
transparent
o Border - A border that goes around the padding and content. The border is affected by the background color of
the box
o Padding – Clears an area around the content. The padding is affected by the background color of the box
o Content- The content of the box, where text and images appear
Advanced CSS
 CSS3 is the latest standard for CSS.
 CSS3 is completely backwards – compatible with earlier versions of CSS.
 CSS3 has been split into "modules". It contains the "old CSS specification" (which has been split into smaller
pieces). In addition, new modules are added.
 CSS3 Transitions are a presentational effect which allow property changes in CSS values, such as those that
may be defined to occur on :hover or :focus, to occur smoothly over a specified duration – rather than
happening instantaneously as is the normal behavior.
 Transition effects can be applied to a wide variety of CSS properties, including background-color, width, height,
opacity, and many more.
 Some of the most important CSS3 modules are:
o Selectors
o Box Model
o Backgrounds and Borders
o Image Values and Replaced Content
o Text Effects
o 2D/3DTransformations
o Animations
o Multiple Column Layout
o User Interface
What is Responsive Web Design?
Responsive web design makes your web page look good on all devices.
Responsive web design uses only HTML and CSS.
Responsive web design is not a program or a JavaScript.
Web pages can be viewed using many different devices: desktops, tablets, and phones. Your web page
should look good, and be easy to use, regardless of the device.
It is called responsive web design when you use CSS and HTML to resize, hide, shrink, enlarge, or move the
content to make it look good on any screen.
What is The Viewport?
The viewport is the user's visible area of a web page.
The viewport varies with the device, and will be smaller on a mobile phone than on a computer screen.
Before tablets and mobile phones, web pages were designed only for computer screens, and it was common
for web pages to have a static design and a fixed size.
Then, when we started surfing the internet using tablets and mobile phones, fixed size web pages were too
large to fit the viewport. To fix this, browsers on those devices scaled down the entire web page to fit the
screen.
What is a Grid-View?
Many web pages are based on a grid-view, which means that the page is divided into rows and columns.
Using a grid-view is very helpful when designing web pages. It makes it easier to place elements on the
page.
A responsive grid-view often has 6 or 12 columns, and will shrink and expand as you resize the browser
window.

CSS Frameworks
CSS Frameworks are pre-written libraries that simplify and speed up the process of designing responsive, visually
consistent web interfaces. They offer ready-to-use components and grid systems, helping developers avoid repetitive
CSS from [Link] provides a solid foundation for buiding modern UIs with less code and better cross-browser
compatiblity. They promote clean design standards, enabling faster prototyping and consistent styling across projects.
CSS frameworks offer several features that make the development process more efficient and effective:
 Efficiency: Pre-designed components and utility classes reduce the time spent writing CSS from scratch.
 Responsive Design: Frameworks are built to adapt to various screen sizes, ensuring your design looks great on
all devices.
 Cross-Browser Compatibility: Ensures consistent appearance across different browsers.
 Customisation: Allows for tailored designs while maintaining a consistent structure.
 Community Support: Large, active communities provide resources and support.
1. Bootstrap
Bootstrap is a popular CSS framework with strong community support, offering pre-designed layouts such
as buttons and navbars, along with utility classes. It is known for its strong community, pre-designed
layouts, and responsive features. The current version is 5.3.2, released on 14 September 2023.
Bootstrap is the most popular CSS framework, developed by Twitter. It is used for responsive grid system
and extensive components. Bootstrap allows for fast and responsive web development. It includes a 12-
column grid, pre-built components like modals, dropdowns, navigation, and more, along with JavaScript-
based elements.
Key Features
 Responsive grid system
 Pre-designed UI components
 Cross-browser compatibility
 JavaScript plugins for interactive elements
2. Tailwind CSS
Tailwind CSS is a utility-first framework that is highly customizable. Instead of offering pre-designed
components, Tailwind provides a set of utility classes that can be used to build custom designs without
writing much CSS.
Key Features
 Utility-first approach for custom designs
 Fully customizable with a configuration file
 No predefined components, offering more control
3. Semantic UI
Semantic UI is an open-source CSS framework with good community support, using classes to add styles
to elements. It offers various components that can be easily integrated into applications to create beautiful
web pages quickly.
Key Features
 Intuitive, human-readable class names
 Pre-built UI components
 Customizable theming system
4. Bulma
Bulma is an open-source CSS framework based on Flexbox, known for its responsiveness and for
minimizing the use of media queries. It is popular for being responsive and cost-effective. The current
version is 0.9.4, released on 8 May [Link] is a modern CSS framework based on Flexbox. It is a
lightweight, easy to use, and customizable. It provides a clean syntax and focuses on making responsive
design easier.
Key Features
 Flexbox-based layout system
 Lightweight and modular
 Clean, simple syntax
5. Skeleton
Skeleton is a minimal CSS framework that focuses on responsive design. It’s small and lightweight,
making it ideal for quick prototyping.
Key Features
 Lightweight, under 400 lines of code
 Simple grid system
 Ideal for quick prototypes

JavaScript:
INTRODUCTIONTO JAVASCRIPT:
Static web pages are useful and can be informative. A number of technologies have been developed
that enable the creation of web applications rather than static web pages. The java programming language
is probably the best known such technology. Few programming languages other than java have been
adapted for use in client-side web applications. One such language that is used in programming client-side
web applications is JavaScript.
JavaScript originates from a language called Live Script and was developed by Sun micro systems
and Netscape navigator. Scripts are small pieces of code which accomplish a single relatively simple task.
JavaScript is a scripting language that is used for the development of Client- side-in-browser applications.
JavaScript is a simple script based language which is only suitable for fairly simple tasks. JavaScript is a
language that is best suited to tasks that run for a short time. Most of the developers experience problems
when they try to build web pages which have embedded javascript.
What is JavaScript?
 HTML and CSS concentrate on a static rendering of a page; things do not change on the page overtime, or because
of events.
 To do these things, we use scripting languages, which allow content to change dynamically.
 Not only this, but it is possible to interact with the user beyond what is possible with HTML.
 Scripts are programs just like any other programming language; they can execute on the client side or the server.
Embedded JavaScript
 JavaScript can be embedded in an HTML document.
 To embed it in HTML you must write:
<script type=”text/java script”>
</script>
 The script tag has effect of the stopping the JavaScript being printed out as well as indentifying the code
enclosed.
 The Java Script can be placed in the head section of your HTML or the body.
<html>
<body>
<script type=”text/java script”> document. Write ("<h1>this is a heading </h1>");
</script>
</body>
</html>
 The Scripts placed in the body section are executed as the page loads and can be used to generate the content
of the page.
 As well as the body section, JavaScript can also be placed in the head part.
 The advantages of putting a script in there are that it loads before the main body.
External JavaScript
 If you want to use the same script on several pages it could be a good idea to place the code in a separate file,
rather than writing it on each.
 That way if you want to update the code, or change it, you only need to do it once.
 Simply take the code you want in a separate file out of your program and save it with the extension
.js.
<html>
<body>
<script src="[Link]"></script>
</body>
</html>
JavaScript Variables
 Variables in JavaScript behave the same as variables in most popular programming languages(C, C++,
etc) do, but in JavaScript you don't have to declare variables before you use them.
 A variable's purpose is to store information so that it can be used later. A variable is a symbolic name
that represents some data that you set.
 When using a variable for the first time it is not necessary to use "var" before the variable name.
 Variable names must begin with a letter.
 Variable names are case sensitive (y and Y are different variables).
var x=5;
var y=6;
var z=x+y;
 You can declare many variables in one statement. Just start the statement with var and separate the
variables by comma:

Var name="Doe",age=30,job="carpenter";
var name="Doe",
age=30,
job="carpenter";
 Variable declared without a value will have the value undefined.
 If you re-declare a JavaScript variable, it will not lose its value.
 The value of the variable car name will still have the value "Volvo" after the execution of the following
two statements.
Var carname="Volvo";
Var carname;
JavaScript Operators
 Operators in JavaScript are very similar to operators that appear in other programming languages.
 The definition of an operator is a symbol that is used to perform an operation.
 Most often these operations are arithmetic(addition, subtraction, etc),but not always.

Operator Name
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
= Assignment
JavaScript Array
 An array is a special variable, which can hold more than one value at a time.
 The Array object is used to store multiple values in a single variable.
 An array can be created in three ways.
 The following code creates an Array object called my Cars.
1. Regular
Var my Cars=new Array();
my Cars[0]="Saab";
my Cars[1]="Volvo";
my Cars[2]="BMW";
2. Condensed
Var my Cars=new Array("Saab","Volvo","BMW");
3. Literal
Var my Cars= ["Saab","Volvo","BMW"];
Access an Array
 You refer to an element in an array by referring to the index number.
 This statement access the value of the first element in my Cars.
Var name=my Cars[0];
 This statement modifies the first element in my Cars:
My Cars[0]="Opel";
JavaScript Functions
 A function is a section of code that is separate from the main program.
 It is defined once but can be invoked many times.
 A function can be passed as parameters so that they can be used and a value can be returned back.
 There are some functions already built into JavaScript, such as the Math. Cos () function, which
calculates the cosine of an angle.
 An example function could be:
functionmultByTen(x)
{
returnx*10;
}

 This can then be invoked by using the function’s name complete with any parameters you want to pass:
My sum=mult By Ten(3)
 Below is an example of JavaScript function.
<html><body>
<script type=”text/javascript”>
var z= mult X by Y(10,15);
[Link](“The result is”+z); function mult X by Y(x,y)
{
[Link](“x is”+x);
[Link](“y is ”+y);
return x*y;
}
</script>
</body></html>
JavaScript alert()
The alert() method in JavaScript is used to display a virtual alert box. It is mostly used to give a warning
message to the users. It displays an alert dialog box that consists of some specified message (which is
optional) and an OK button. The syntax is:
alert ("message");
JavaScript prompt()
The prompt() method in JavaScript is used to display a prompt box that prompts the user for the input. It is
generally used to take the input from the user before entering the page. When the prompt box pops up, we
have to click "OK" or "Cancel" to proceed. Syntax is:
prompt("message"," default");
JavaScript Statements:
Programs are composed of data and code which manipulates that data. Program instructions are
grouped into units called statements. We create programs from lot of statements.
If-else:
The JavaScript if-else statement is used to execute the code whether condition is true or false. There are
three forms of if statement in JavaScript.
 if Statement
 if else statement
 if else if statement
If statement:
It evaluates the content only if expression is true. The signature of JavaScript if statement is:
if(expression)
{
//content to be evaluated
}
Example:
<html>
<head>
<title>If statement</title>
</head>
<body bgcolor="pink">
<script type="text/javascript">
Var age=parseInt(prompt("Enter age of the person",""));
if(age>60)
{
[Link]("<h1>Senior Citizen</h1>");
}
</script>
</body>
</html>
JavaScript If...else Statement:
It evaluates the content whether condition is true of false. The syntax of JavaScript if-else statement
is:
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
Example:
<html>
<head>
<title>If statement</title>
</head>
<body bgcolor="pink">
<script language="javascript">
Var n= parseInt(prompt("Enter a value",""));
if(n%2==0){
[Link](n+"is even number");
}
else{
[Link](n+"is odd number");
}
</script>
</body>
</html>
JavaScript If...else if statement:
It evaluates the content only if expression is true from several expressions. The signature of
JavaScript if else if statement is:
if(expression1){
//content to be evaluated if expression1is true
}
Else if(expression2){
//content to be evaluated if expression2 is true
}
Else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}
Example
:
<html>
<head>
<title>if statement</title>
</head>
<body bgcolor="pink">
<script language="javascript">
Var m1=parseInt(prompt("EnterMarks1","0"));
Var m2=parseInt(prompt("EnterMarks2","0"));
Var m3=parseInt(prompt("EnterMarks3","0"));
var avg=parseInt((m1+m2+m3)/3);
if(avg>70){ [Link]("<h1>Distinction</h1>");
}
else if(avg<70&&avg>60){ [Link]("<h1>FirstClass</h1>");
}
else if(avg<60&&avg>50){ [Link]("<h1>Secondclass</h1>");
}
else{ [Link]("<h1>Fail</h1>");
}
</script>
</body>
</html>
JavaScript Switch:
The JavaScript switch statement is used to execute one code from multiple expressions. The signature of
JavaScript switch statement is:
Switch (expression){
casevalue1:
code to be executed; break;
casevalue2:
code to be executed; break;
......
default:
code to be executed if above values are not matched;
}
Example:
<html>
<head>
<title>Switch</title>
</head>
<body bgcolor="pink">
<script language="javascript">
Var a=parseInt(prompt("Enter a value",""));
var b=parseInt(prompt("Enter b value",""));
Var ch=parseInt(prompt("Enter your choice",""));
switch(ch){
case1: [Link]("<h1>Additionis:"+(a+b)+"<h1>");
break;
case2: [Link]("<h1>Subtractionis:"+(a-b)+"<h1>");
break;
case3: [Link]("<h1>Multiplicationis:"+(a*b)+"<h1>");
break;
case4:[Link]("<h1>Divisionis:"+(a/b)+"<h1>");
break;
default: [Link]("<h1>Invalid Choice</h1>");
}
</script>
</body>
</html>
JavaScript Loops:
The JavaScript loops are used to iterate the piece of code. Various types of loops are:
1. for loop
2. while loop
3. do-while loop
JavaScript For loop:
The JavaScript for loop iterates the elements for the fixed number of times. Syntax is:
for (initialization; condition; increment)
{
Code to be executed
}
JavaScript while loop:
The JavaScript while loop iterates the elements for the infinite number of times. Syntax is:
while (condition)
{
Code to be executed
}
JavaScript do while loop:
The JavaScript do while loop iterates the elements for the infinite number of times like while loop. But,
code is executed at least once whether condition is true or false. Syntax is:
Do
{
code to be executed
}
while (condition);
Example:
<html>
<head>
<title>Multiplication</title>
</head>
<bodybgcolor="pink">
<script language="javascript">
varn=parseInt(prompt("Enteranumber",""));
var i;
for(i=1;i<=10;i++){
[Link]("<b>"+n+"*"+i+"="+(n*i)+"<br>");
}
</script>
</body>
</html>
Simple form validation:
<html>
<head>
<title>Validation</title>
<script language="javascript">
function validate()
{
Var value= [Link][0].elements[0].value;
if(value!="abc")
{
[Link][0].reset();
}
else{
alert("Hi abc");
}
}
</script>
</head>
<body bgcolor="pink">
<form>
Name:<input type="text" name="txt 1" value=""> <br>
<input type="submit" value="Submit" onClick="validate()">
</form>
</body>
</html>
Module 2
Git and GitHub Fundamentals
In the world of software development, over 90% of developers use a version control system, with Git being
the most popular choice. Git is a distributed version control system that allows developers to track changes
in code, collaborate seamlessly, and manage projects efficiently. GitHub is built on top of Git, a cloud-based
platform that provides a user-friendly interface for hosting, reviewing, and sharing code. Together, Git and
GitHub have become essential for modern development, enabling open-source collaboration and enterprise-
level project management.

Introduction to Git
A version Control system is a system that maintains different versions of your project when working in a
team or as an individual. (System managing changes to files) As the project progresses, new features get
added to it. So, a version control system maintains all the different versions of your project for you, and you
can roll back to any version you want without causing any trouble to you for maintaining different versions
by giving names to them, like MyProject, MyProjectWithFeature1, etc.
Distributed Version control system means every collaborator (any developer working on a team
project)has a local repository of the project in his/her local machine unlike central where team members
should have an internet connection to every time update their work to the main central repository.
So, by distributed we mean: the project is distributed. A repository is an area that keeps all your project files,
images, etc. In terms of GitHub: different versions of projects correspond to commits.
Git Concepts
 Repository- A directory where git monitors your project files and records their revision history.
 Clone- It created a local copy of a remote repository on your machine.
 Stage - It selects specific changes that you want Git to include in the next snapshot.
 Commit- It records the staged changes as a permanent version in the project history.
 Branch- Lets you develop new features or experiment without affecting the main project.
 Merge- Integrates changes from one branch into another.
 Pull- It fetches and applies updates from a remote repository to your local one.
 Push- It Uploads your local commits to a remote repository
Git Repository Structure
It consists of 4 parts:
1. Working directory: This is your local directory where you make the project (write code) and make
changes to it.
2. Staging Area (or index): this is an area where you first need to put your project before committing.
This is used for code review by other team members.
3. Local Repository: this is your local repository where you commit changes to the project before
pushing them to the central repository on Github. This is what is provided by the distributed version
control system. This corresponds to the .git folder in our directory.
4. Central Repository: This is the main project on the central server, a copy of which is with every team
member as a local repository.
All the repository structure is internal to Git and is transparent to the developer.
Some commands which relate to repository structure:
// transfers your project from working directory
// to staging area.
git add .
// transfers your project from staging area to
// Local Repository.
git commit -m "your message here"

// transfers project from local to central repository.


// (requires internet)
git push
Working with existing repos(git clone) and new repos(git init)
Git allows you to manage existing repository as well as new [Link] can clone remote repository to work
on a project that already exists, or initialize a new repository to begin tracking changes in a fresh project.
 Working with existing repos (git clone)- When you are collaborating on a project that already exists on
the remote platform like Github, you don't need to start from scratch . Instead you can clone the
repository to your local machine using:
git clone <repository-url>
This commands downloads the entire repository including its history, branches, and files.
git clone [Link]
Now you have a full copy of the project and can start contributed locally.
 Started a new Repository (git init) - If you are beginning a brand new project you use:
git init
This Command will create a new git repository in your current directory. It sets up a . git folder that will
track all your changes made to files inside the project.
mkdir my-project
cd my-project
git init
it will create a new folder , cd will redirect to current directory and git init will initializes a new empty
repository.
How to Use git merge Effectively in Git
git merge is used to combine changes from one branch into another. It allows teams to work on different
features or fixes in isolation and then bring work together . Merging Preserves the history of both branches
and is a key part of collaborative workflows in git.
 Switch the branch you want to merge into your changes
git checkout main
 Merge Changes from another branch into the current branch
git merge feature-branch
 If there are merge conflicts resolve them manually, then stage the changes
git add .
 Commit the merge if conflicts were resolved manually
git commit
Creation of new Branch
Branches allow you to work on new features or fixes independently without affecting the main codebase.
This isolates works and makes collaboration easier.
git branch branch-name
Creating a new Branch without switching to it.
 View All Branches
git branch
Deletion of Branches
Once a branch has been emerged or no longer needed, you can delete it to keep your repo clean and
organized.
 Delete a local branch
git branch -d branch-name
Deletes the branch if it has already been merged.
 Force delete a local branch(unmerged changes)
git branch -D branch-name
Delete the branch regardless of its mege status
 Delete a remote branch
git push origin --delete branch-name
Removes the branch from the remote repository (e.g., GitHub).
How to Use git fetch Effectively in Git
git fetch is used to download latest changes from a remote repository without automatically merging them
into your current branch. It updates your local view of the remote branches, so you can review or merge
changes .
 Fetch all branch from the remote
git fetch
Download update from the default remote (usually origin)
 Fetch from a specific remote
git fetch origin
 Fetch from a specific branch
git fetch origin feature-branch
Fetches only the feature-branch from the remote.
 View changes after fetching
git log HEAD..origin/main
It shows changes to your main branch that aren't not in your local branch.
How to Use git stash Effectively in Git
git stash is a handy git command that lets you temporarily save your uncommitted changes(both staged
and unstaged) so you can switch branches or perform other tasks without losing your work. Once you're
ready, you can reapply those changes exactly as you left them.
 Stash your current changes
git stash
Saves your changes and reverts your working directory to a clean state.
 Stash with a custom message(recommended)
git stash save "WIP: added login form"
Adds a label so you remember what was stashed.
 View list all stashes
git stash list
Displays stashes like stash@{0}, stash@{1}, etc.
 Apply the most recent stash
git stash apply
Restores the changes but keeps the stash in the list.
 Apply a specific stash
git stash apply stash@{1}
 Apply and delete a stash in one step
git stash pop
 Clear all stash
git stash clear
It removes all saved stashes.
Github
Github basically is a for-profit company owned by Microsoft, which hosts Git repositories online. It helps
users share their git repository online, with other users, or access it remotely. You can also host a public
repository for free on Github.
User share their repository online for various reasons including but not limited to project deployment,
project sharing, open source contribution, helping out the community and many such.
Accessing Github central repository via HTTPS or SSH
Here, transfer project means transfer changes as git is very lightweight and works on changes in a project.
It internally does the transfer by using Lossless Compression Techniques and transferring compressed
files. Https is the default way to access Github central repository.
 By git remote add origin http_url: remote means the remote central repository. Origin corresponds to
your central repository which you need to define (hereby giving HTTPS URL) in order to push changes
to Github.
 Via SSH: connect to Linux or other servers remotely.
If you access Github by ssh you don't need to type your username and password every time you push
changes to GitHub.
Terminal commands:
ssh-keygen -t rsa -b 4096 -C "your_email@[Link]"
This does the ssh key generation using RSA cryptographic algorithm.

eval "$(ssh-agent -s)" -> enable information about local login session.

ssh-add ~/.ssh/id_rsa -> add to ssh key.


cat ~/.ssh/id_rsa (use .pub file if not able to connect)
add this ssh key to github.

Now, go to github settings -> new ssh key -> create key

ssh -T git@[Link] -> activate ssh key (test connection)

Refresh your github Page.


Working with git - Important Git commands
Git user configuration (First Step)
git --version (to check git version)
git config --global [Link] "your name here"
git config --global [Link] "your email here"
These are the information attached to commits.
Initialize directory
git init
initializes your directory to work with git and makes a local repository. .git folder is made (OR)
git clone http_url
This is done if we have an existing git repository and we want to copy its content to a new place.
Connecting to the remoterepository
git remote add origin http_url/ssh_url
connect to the central repo to push/pull. pull means adopting the changes on the remote repository to your
local repository. push merges the changes from your local repository to the remote repository.
git pull origin master
One should always first pull contents from the central repo before pushing so that you are updated with
other team members' work. It helps prevent merge conflicts. Here, master means the master branch (in
Git).
Stash Area in git
git stash
Whichever files are present in the staging area, it will move that files to stash before committing it.
git stash pop
Whenever we want files for commit from stash we should use this command.
git stash clear
By doing this, all files from stash area is been deleted.
Steps to add a file to a remote Repository:
First, your file is in your working directory, Move it to the staging area by typing:
git add -A (for all files and folders)
#To add all files only in the current directory
git add .
git status: here, untracked files mean files that you haven't added to the staging area. Changes are not
staged for commit means you have staged the file earlier than you have made changes in that files in your
working directory and the changes need to be staged once more. Changes ready to be committed: these are
files that have been committed and are ready to be pushed to the central repository.
git status
git commit -a -m "message for commit"
-a: commit all files and for files that have been
staged earlier need not to be git add once more
-a option does that automatically.
git push origin master -> pushes your files to
github master branch
git push origin anyOtherBranch -> pushes any
other branch to github.
git log ; to see all your commits
git checkout commitObject(first 8 bits) [Link]->
revert back to this previous commit for file [Link]
Previous commits might be seen through the git log command.
HEAD -> pointer to our latest commit.
Ignoring files while committing
In many cases, the project creates a lot of logs and other irrelevant files which are to be ignored. So to
ignore those files, we have to put their names in".gitignore" file.
touch .gitignore
echo "[Link]" >>.gitignore
#to ignore all files with .log extension
echo "*.log" > .gitignore
Now the filenames written in the .gitignore file would be ignored while pushing a new commit. To get the
changes between commits, commit, and working tree.
git diff
The 'git diff' command compares the staging area with the working directory and tells us the changes
made. It compares the earlier information as well as the current modified information.
Branching in Git
create branch ->
git branch myBranch
or
git checkout -b myBranch -> make and switch to the
branch myBranch
Do the work in your branch. Then,
git checkout master ; to switch back to master branch
Now, merge contents with your myBranch By:
git merge myBranch (writing in master branch)
This merger makes a new commit.

Another way
git rebase myBranch
This merges the branch with the master in a serial fashion. Now,
git push origin master
To remove or delete a file
To remove. a file from the Git repository we use
git rm “file name”
To remove only from the staging area
git rm –cached “ file name”
Undoing change
To change all the files to as same as the previous commit then use
git checkout -f
Git vs Github
Git and GitHub are often mentioned together, but they serve different purposes. Git is a local tool used for
tracking changes in your code, while GitHub is an online platform for hosting and sharing Git
repositories. Together, they enable powerful version control and team collaboration in software
development.
Feature Git Github

Type Version control system (VCS) Web based Hosting Service

Function Tracks and manages code changes Stores Git repositories in the cloud and enables
locally collaboration

Installation Must be installed on your system Accessible through a web browser (no installation
needed)

Usage Used for local version control and Used for sharing, reviewing, and managing Git
branching projects online

Collaboration Limited to local or manual sharing Real-time collaboration with teams and
contributors

Interface Command-line tool (CLI) Web-based UI and also supports Git CLI

Main Purpose Track code history and manage Centralized hub to host, view, and contribute to
changes locally Git projects

Offline Fully functional offline Requires internet to access remote features


Support

This self paced introductory course provides an in depth understanding of git and github?
Common features of such courses include:
 Git Fundamentals:
Explanation of Git's core principles, including repositories, commits, and the Git workflow.
 Git Commands:
Practical instruction on essential Git commands for managing code, such as git init, git add, git
commit, git push, git pull, and git clone.
 Branching and Merging:
Understanding how to create and manage branches for parallel development, and how to merge changes
back into the main codebase.
 GitHub Collaboration:
Learning to use GitHub for team collaboration, including creating pull requests, reviewing code, and
managing issues.
 Remote Repositories:
Working with remote repositories on platforms like GitHub to store and share code.
 Hands-on Practice:
Many courses incorporate practical exercises and projects to reinforce learning and build real-world
skills.
Examples of such courses include:
 Getting Started with Git and GitHub
offered by institutions like IBM on platforms such as Cognitive Class and Coursera.
 Introduction to Git and GitHub
as part of professional certificates, like the Google IT Automation with Python Professional Certificate on
Coursera.
 Learn Git & GitHub
from platforms like Codecademy, focusing on interactive lessons and projects.
 The Ultimate Git Course
by instructors like Code with Mosh, covering both essentials and advanced techniques.
Essential tools for collaboration and social coding in modern software engineering and
devOps culture?
Essential tools for modern software engineering collaboration and social coding include version control platforms
like GitHub, GitLab, and Bitbucket; communication tools such as Slack; project management software like Jira and
Asana; and documentation and knowledge-sharing platforms like Confluence. These tools facilitate code versioning,
real-time communication, task tracking, and centralized documentation, which are critical for both social coding and
DevOps workflows.
Version Control and Code Collaboration
 Git: The foundational distributed version control system.
 GitHub / GitLab / Bitbucket: Platforms built on Git that provide a central hub for hosting code repositories,
managing issues, and facilitating code reviews and pull requests.
Communication and Chat
 Slack / Microsoft Teams: Real-time messaging platforms that enable instant conversations, project-specific
channels, and integrations with other development tools.
 Zoom: Essential for remote teams to conduct virtual meetings like stand-ups, retrospectives, and sprint reviews.
Project Management and Planning
 Jira: Widely used for agile project management, bug tracking, and visualizing workflows across sprints and
iterations.
 Asana / Trello: Other popular tools for project and task management, helping teams organize and visualize their
work.
Documentation and Knowledge Sharing
 Confluence: A collaborative wiki and documentation platform that serves as a central knowledge base for teams.
 Jira / Bitbucket: Both platforms include features for managing issues and project documentation directly within
their interfaces.
DevOps Automation and Continuous Integration/Continuous Delivery (CI/CD)
 GitHub Actions / GitLab CI/CD: Integrated CI/CD capabilities within code hosting platforms to automate
workflows.
 Jenkins: A popular open-source automation server that can automate parts of the build, test, and deploy process.
 Terraform / Ansible: Tools for infrastructure as code and configuration management, allowing teams to version
and automate their infrastructure.
 Docker / Kubernetes: Containerization tools that allow teams to package applications and their dependencies and
deploy them consistently across different environments.
The course includes hands on labs git and github?
A course that includes hands-on labs for Git and GitHub will provide practical experience in version control
and collaborative software development
Hands-on Labs:
The "hands-on labs" aspect emphasizes practical application. This means learners will actively engage with Git and
GitHub through:
 Setting up Repositories: Creating and configuring both local Git repositories and remote GitHub repositories.
 Committing Changes: Practicing the process of tracking and committing changes to files.
 Branch Management: Creating, switching between, and merging branches in various scenarios.
 Collaborative Workflows: Participating in simulated or actual collaborative projects, including creating pull
requests and resolving merge conflicts.
 Real-world Scenarios: Applying Git and GitHub skills to practical problems and project management tasks.
Fostering team productivity on github
Fostering team productivity on GitHub involves leveraging its features for streamlined collaboration,
efficient workflow management, and clear communication.
1. Structure and Organization:
 Utilize GitHub Organizations and Teams:
Group team members into logical teams within an organization to manage access permissions to
repositories and facilitate targeted communication and notifications.
 Establish Clear Repository Structure:
Organize codebases within well-defined repositories and use branches effectively for feature
development, bug fixes, and releases.
 Implement Project Boards and Issues:
Use GitHub Project boards for visual task management and tracking progress. Create detailed issues for
bugs, features, and tasks, leveraging labels, assignees, and milestones for clarity and prioritization. Sub-
issues can further break down larger tasks.
2. Workflow and Automation:
 Automate with GitHub Actions:
Set up CI/CD pipelines, automate testing, code quality checks, and deployment processes using GitHub
Actions to reduce manual effort and ensure consistency.
 Leverage Pull Requests (PRs) for Code Review:
Encourage thorough code reviews using PRs, providing constructive feedback and ensuring code quality
before merging.
 Integrate with External Tools:
Connect GitHub with other tools used by the team (e.g., communication platforms like Slack or Microsoft
Teams) for seamless notifications and information flow.
3. Communication and Collaboration:
 Foster Active Communication in Issues and PRs:
Encourage team members to discuss challenges, share updates, and make decisions directly within
issues and PRs, creating a transparent and traceable record.
 Utilize Discussions for Open-Ended Brainstorming:
For broader discussions, feedback, or open-ended brainstorming not tied to specific code changes,
leverage GitHub Discussions.
 Establish Clear Communication Norms:
Define expectations for response times, code review etiquette, and how different types of communication
should be handled within GitHub.
4. Continuous Improvement and Learning:
 Monitor and Analyze Activity (with caution):
Track relevant metrics like pull request merge times or issue resolution rates to identify bottlenecks and
areas for improvement, but avoid using metrics for individual performance evaluation.
 Encourage Knowledge Sharing:
Create internal documentation within repositories or wikis to capture best practices, architectural
decisions, and common solutions.
 Provide Training and Resources:
Ensure team members are proficient with GitHub's features and best practices through training or by
providing access to relevant resources.
Building Your Stunning GitHub Portfolio: A Step-by-Step Guide
Step 1: Set Up a GitHub Account
If you don’t have a GitHub account, create one at [Link]. It’s the go-to platform for version
control and hosting projects.
Step 2: Create a New Repository
1. Click on the ‘+’ sign in the top right corner.
2. Select ‘New Repository.’
3. Name your repository as [your-username].[Link]. This is crucial for GitHub Pages to work.
Step 3: Choose a Theme
GitHub Pages supports Jekyll themes. Navigate to the ‘Settings’ tab in your repository and
scroll down to the ‘GitHub Pages’ section. Choose a theme to give your portfolio a polished look.
Step 4: Customize Your Portfolio
1. Access your repository’s code.
2. Open the _config.yml file to configure settings such as your name, bio, and social media links.
3. Add or edit Markdown files in the _posts directory to showcase your projects.
Step 5: Project Pages
Create a new directory for each project. Include an [Link] file with project details, images, and
code snippets. Link these project pages from your main portfolio page.
Step 6: Local Testing with Jekyll (Optional)
If you want to test your site locally, install Jekyll by following the official guide. Run bundle exec
jekyll serve in your project directory and access [Link] in your browser.
Step 7: Commit and Push Changes
Once satisfied with your changes, commit them to your repository and push to GitHub.
git add .
git commit -m "Add project pages and customize portfolio"
git push origin master
Step 8: Access Your Portfolio
Visit [your-username].[Link] in your browser. Voilà! Your portfolio is live.
Tips for a Standout Portfolio:
 Clear Introduction: Briefly introduce yourself and your skills.
 Project Showcase: Highlight key projects. Include project descriptions, technologies used,
and links to the GitHub repositories or live demos.
 Blog Section (Optional): Share your insights and experiences in the tech world.
 Contact Information: Make it easy for visitors to get in touch.
Providing a valuable addition to their resume github skills
1. Showcase Relevant Projects:
 Highlight key projects:
Select projects that align with the target job's requirements and demonstrate proficiency in relevant technologies
and languages.
 Provide clear descriptions:
Each project should have a concise and informative [Link] file explaining its purpose, technologies used, and
how to run or interact with it.
 Emphasize impact and results:
If possible, quantify achievements within projects (e.g., improved performance by X%, reduced errors by Y%).
2. Demonstrate Git Proficiency:
 Consistent contributions:
Maintain an active GitHub profile with regular commits, showcasing consistent engagement and development.
 Branching and merging:
Utilize effective branching strategies for feature development and demonstrate clean merging practices.
 Pull requests and code reviews:
Engage in pull requests, both creating and reviewing, highlighting collaboration and attention to code quality.
 Issue tracking and project management:
Demonstrate experience with GitHub's issue tracking features for managing tasks and bugs.
3. Emphasize Collaboration and Open Source:
 Contributions to open-source projects:
Participation in open-source projects demonstrates a willingness to collaborate and contribute to the wider
developer community.
 Team projects:
Highlight projects where collaboration was a key element, showcasing teamwork and communication skills.
4. Optimize Your GitHub Profile:
 Professional profile picture and bio:
Use a professional image and a concise, informative bio that reflects your skills and career aspirations.
 Pinned repositories:
Pin your most impressive and relevant projects to the top of your profile for easy visibility.
 Organized repositories:
Maintain clear and well-structured repositories with appropriate naming conventions and file organization.
5. Integrate GitHub into Your Resume:
 Include your GitHub profile link:
Place a clear and accessible link to your GitHub profile in your contact information or a dedicated "Portfolio"
section.
 Mention specific projects:
In your "Experience" or "Projects" section, briefly describe key GitHub projects and link directly to their repositories.
 List "Git" and "GitHub" in your skills section:
Include these as technical skills, potentially alongside other version control systems or collaboration tools.
Module 3
Developing Front-End Apps with React
Advanced ReactJS
ReactJS is a popular library for building modern user interfaces. While many developers are familiar with
its basic concepts like components, state, and props, there are advanced features that can take your React
apps to the next level. By exploring these features, you can optimize performance, manage complex
states, and create more dynamic, efficient, and scalable applications.
Rendering and Re-rendering in React
In React, rendering and re-rendering are key concepts to understand, as they directly affect how efficiently
your app updates and displays content.
Rendering in React
Rendering is the process where React takes the component's data (state and props) and turns it into a UI that
the user can interact with. When a component is first loaded, React renders the component and displays it in
the DOM.
import React from "react";

function MyComp() {
return <h1>Hello, World!</h1>;
}

export default MyComponent;


In this code
 React functional component called MyComponent.
 It returns JSX that renders the text "Hello, World!" inside an <h1> element.
 The component is exported using export default so it can be imported and used in other parts of the
application.
Re-rendering in React
Re-rendering happens when the state or props of a component change. React will trigger a re-render to
reflect the updated data in the UI. However, React optimizes this process to avoid unnecessary re-renders.
When Does Re-rendering Happen
 Re-rendering occurs when: State changes: If the component’s internal state (useState, setState)
changes, React will re-render the component to show the new state.
 Props change: If the props passed to the component change, React re-renders that component to reflect
the new props.
Real and Virtual DOM
Real DOM: The Real DOM is the actual representation of the UI in the browser. It’s a programming
interface for web documents and represents the structure of a webpage as a tree of elements.
 Slower Updates: When the state or data changes in a web application, the entire DOM may need to be
updated.
 Direct Manipulation: The Real DOM is updated directly. When a change is made, the browser updates
the actual page, often causing reflows and repaints, which can be resource-intensive.
 Heavy Operations: Modifying the Real DOM can trigger heavy operations like layout recalculations,
which makes direct manipulation of the Real DOM inefficient, especially for large applications.
Virtual DOM: The Virtual DOM is a lightweight, in-memory representation of the Real DOM. It’s an
abstraction that React uses to optimize the process of updating the UI. Rather than manipulating the Real
DOM directly, React updates the Virtual DOM first and then compares it with the previous version to
efficiently apply the minimal number of changes to the Real DOM. This process is called reconciliation.
 Faster Updates: The Virtual DOM allows React to perform batch updates. It avoids direct manipulation
of the Real DOM, making updates much faster.
 Efficient Rendering: React uses a diffing algorithm to compare the Virtual DOM with the Real DOM
and calculates the minimal set of changes needed to update the UI.
 No Reflows or Repaints: By updating only what is necessary, React avoids reflows and repaints, which
are costly operations in the Real DOM.
Higher-Order Components (HOCs)
Higher-Order Components (HOCs) are a powerful pattern in React. HOCs are functions that take a
component and return a new component with additional props. They are typically used for cross-cutting
concerns like authentication, logging, or data fetching, providing reusable functionality.
[Link]

import React from 'react';


import DisplayMessage from './DisplayMessage';
import withLogging from './withLogging';

const EnhancedDisplayMessage = withLogging(DisplayMessage);

function App() {
return (
<div>
<h1>React App with Higher-Order Component (HOC)</h1>
<EnhancedDisplayMessage message="Hello, World!" />
</div>
);
}

export default App;

[Link]

import React from 'react';

function withLogging(WrappedComponent) {
return function msg(props) {

[Link]('Rendering Enhanced Component with props:', props);

// Render the wrapped component


return <WrappedComponent {...props} />;
};
}

export default withLogging;

[Link]

import React from 'react';

function DisplayMessage({ message }) {


return <h1>{message}</h1>;
}

export default DisplayMessage;

React Context API


The Context API allows you to share values between components without explicitly passing props down
through every level of the tree. It is ideal for state that needs to be accessed by many components, such as
themes or authentication status.
[Link]
import React from 'react';
import MyContext from './MyContext'; // Import the created context
import ChildComponent from './ChildComponent'; // Import the child component

function App() {
return (
<[Link] value="Hello from Context!">
<div>
<h1>React Context API Example</h1>
<ChildComponent />
</div>
</[Link]>
);
}

export default App;

[Link]

import React from 'react';

// Create a Context with a default value


const MyContext = [Link]('Default Value');

export default MyContext;

[Link]

import React, { useContext } from 'react';


import MyContext from './MyContext';

function ChildComponent() {
const contextValue = useContext(MyContext);
[Link]('Context Value:', contextValue);
return <p>{contextValue}</p>;
}

export default ChildComponent;

React Suspense and Lazy Loading


The [Link]() function is used to dynamically import a component. This enables code splitting, where
the components are loaded only when they are required.
 [Link](): This is used to define the LazyComponent. It will only load the component when it is
required (i.e., when it’s rendered).
const LazyComponent = lazy(() => import('./LazyComponent'));
 Suspense: This is a wrapper around the lazy-loaded component. It displays a fallback (such as a
loading spinner or a message) while the component is being loaded asynchronously.
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
Performance Optimization in React
Optimizing the performance of a React application is crucial to ensure it runs smoothly, especially for
larger applications with complex UIs and state management. Here are the key strategies and best practices
for performance optimization in React:
1. Memoization of Components: [Link](): [Link]() is a higher-order component (HOC) that
helps to prevent unnecessary re-renders of a component. It wraps a component and only re-renders it if its
props change.
Syntax
const MyComponent = [Link](function MyComponent({ count }) {
[Link]('Rendering MyComponent');
return <p>Count: {count}</p>;
});
2. Using useCallback for Memoizing Functions: The useCallback hook memoizes functions and ensures
they are not re-created on every render. This is useful when passing functions as props to child
components, especially when those functions are used inside a [Link]() wrapped component.
const increment = useCallback(() => setCount(count + 1), [count]);
return <ChildComponent increment={increment} />;
}
Redux
React-Redux is a popular state management library that helps manage the application state in React
applications. It helps manage an application's state in a centralized way, making it easier to maintain and
debug, especially as the app grows in complexity.
It is based on three fundamental principles:
Single Source of Truth: The entire application state is stored in a single JavaScript object called the store.
State is Read-Only: The only way to change the state is by dispatching an action that describes the change.
Changes are Made with Pure Functions: Changes to the state are made using reducers, which are pure
functions that take the previous state and an action, and return the new state.

State Management with Redux


Redux is a predictable state container for JavaScript apps. It is ideal for managing the global state of the
app. Redux allows you to centralize the state and dispatch actions to update the state.
Steps involved in Redux
 Store: Holds the state.
 Actions: Describe what happened.
 Reducers: Specify how the state changes in response to actions.

[Link]

import React from 'react';


import { useSelector, useDispatch } from 'react-redux';
import { increment } from './actions';

const App = () => {


const count = useSelector(state => [Link]); // Select only count
const dispatch = useDispatch();

return (
<div>
<h1>{count}</h1>
<button onClick={() => dispatch(increment())}>Increment</button>
</div>
);
};

export default App;


[Link]
export const increment = () => ({
type: 'INCREMENT',
});
[Link]

const initialState = {
count: 0,
theme: 'light',
};

const counterReducer = (state = initialState, action) => {


switch ([Link]) {
case 'INCREMENT':
return { ...state, count: [Link] + 1 };
case 'TOGGLE_THEME':
return { ...state, theme: [Link] === 'light' ? 'dark' : 'light' };
default:
return state;
}
};

export default counterReducer;

[Link]

import { createStore } from 'redux';


import counterReducer from './reducer';

const store = createStore(counterReducer);

export default store;

Error Boundaries
Error Boundaries are React components that catch JavaScript errors anywhere in their child component
tree, log those errors, and display a fallback UI instead of crashing the whole app.

[Link]

import React from 'react';


import ErrorBoundary from './ErrorBoundary';
import BuggyComponent from './BuggyComponent';

function App() {
return (
<div>
<h1>React Error Boundaries Example</h1>

{/* Wrap BuggyComponent in ErrorBoundary */}


<ErrorBoundary>
<BuggyComponent />
</ErrorBoundary>
</div>
);
}

export default App;


[Link]

import React, { Component } from 'react';

class ErrorBoundary extends Component {


constructor(props) {
super(props);
[Link] = { hasError: false, errorMessage: '' };
}

static getDerivedStateFromError(error) {
// Update state to show fallback UI
return { hasError: true, errorMessage: [Link] };
}

componentDidCatch(error, info) {
// Log the error for debugging (optional)
[Link]('Error caught by ErrorBoundary:', error);
[Link]('Error information:', info);
}

render() {
if ([Link]) {
// Fallback UI if there is an error
return (
<div>
<h1>Something went wrong:</h1>
<p>{[Link]}</p>
</div>
);
}

return [Link]; // Render children if no error


}
}

export default ErrorBoundary;

[Link]

import React, { useState } from 'react';

function BuggyComponent() {
const [count, setCount] = useState(0);

if (count === 5) {
// Simulate an error when count is 5
throw new Error('I crashed!');
}

return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

export default BuggyComponent;

Reconciliation Algorithm
The Reconciliation Algorithm in React is the process of comparing the new Virtual DOM with the
previous one and determining the minimal set of changes required to update the Real DOM efficiently.
This is important for React’s performance, as it allows React to make updates with minimal computational
overhead, resulting in faster rendering.
How Reconciliation Works in React?
When the state or props of a React component change, React needs to update the UI. Here’s how the
Reconciliation process works step-by-step:
 Virtual DOM Creation: When a component is rendered, React first creates a Virtual DOM (an in-
memory representation of the real DOM) to describe what the UI should look like.
 Change in State/Props: When the state or props of a component change (e.g., through setState() or
useState()), React triggers a re-render of that component.
 New Virtual DOM Tree: React creates a new Virtual DOM based on the updated state or props. This
tree represents the desired UI after the update.
 Comparison (Diffing): React compares the new Virtual DOM tree with the previous one. This process
is known as "diffing". React uses a series of heuristics to make this comparison more efficient.
 Minimal Updates to Real DOM: After identifying the differences (or "diffs") between the old and
new Virtual DOM, React applies the minimal set of changes to the Real DOM. These are the "patches"
that update the actual page on the screen.
Server-Side Rendering (SSR) and Static Site Generation (SSG)
Server-Side Rendering (SSR) and Static Site Generation (SSG) are techniques that pre-render content on
the server side to improve SEO and performance. React supports SSR with frameworks like [Link],
which provides an easy-to-use setup for building applications with SSR and SSG.
1. Server-Side Rendering (SSR):
Server-Side Rendering is a technique where the HTML for a page is generated on the server at the time
the request is made by the user, rather than in the browser.
How SSR Works
 When a user requests a page (for example, by visiting a URL), the server generates the HTML content
for that page on the fly.
 The server sends the fully rendered HTML to the browser, which then displays the content to the user.
 Once the initial HTML is loaded, JavaScript runs on the client-side to make the page interactive (by
attaching event listeners, fetching data, etc.).
2. Static Site Generation (SSG):
Static Site Generation is a technique where the HTML for a page is generated at build time instead of
runtime. The pages are pre-rendered into static HTML files that are served to the user.
How SSG Works
 During build time, all pages of the website are rendered into static HTML files.
 These static files are saved and served by the server or CDN (Content Delivery Network) when
requested by the user.
 The user receives the static HTML immediately, and JavaScript is used for adding interactivity on the
client side.
React Hooks: Advanced Usage
 useReducer: Manage complex state logic in functional components.
 useCallback & useMemo: Optimize performance by memoizing functions and values.
 Custom Hooks: Reuse logic across components efficiently.
Building Rich Front-End Applications with React and ES6
Building Rich Features:
 State Management: For complex applications, libraries like Redux or the React Context API can be used to manage
global application state effectively.
 Routing: React Router is a popular library for managing navigation and different views within a single-page
application.
 API Integration: Fetching data from external APIs using fetch or libraries like Axios to populate and update the UI.
 User Interface Libraries: Utilizing UI component libraries (e.g., Material-UI, Ant Design, Chakra UI) to accelerate
development and ensure consistent design.
 Performance Optimization: Techniques like memoization (e.g., [Link], useMemo), code splitting, and lazy
loading to improve application speed and responsiveness.
Development Workflow:
 Setup: Use create-react-app or a build tool like Vite to quickly set up a new React project with a pre-configured
development environment.
 Component Development: Break down the UI into smaller, manageable components, leveraging functional
components and Hooks where appropriate.
 State and Data Management: Implement state management strategies, whether local component state, Context
API, or a library like Redux.
 Styling: Apply styles using CSS, CSS-in-JS libraries, or pre-processors like Sass.
 Testing: Write unit and integration tests for components and application logic using tools like Jest and React Testing
Library.
 Deployment: Build the application for production and deploy it to a hosting platform.

React Components
In React, components are reusable, independent code blocks (A function or a class) that define the
structure and behavior of the UI. They accept inputs (props or properties) and return elements that
describe what should appear on the screen.
Key Concepts of React Components:
 Each component handles its own logic and UI rendering.
 Components can be reused throughout the app for consistency.
 Components accept inputs via props and manage dynamic data using state.
 Only the changed component re-renders, not the entire page.
Example:
import React from 'react';
// Creating a simple functional component
function Greeting() {
return (
<h1>Hello, welcome to React!</h1>
);
}
export default Greeting;
Output:
Hello, welcome to React!
Types of React Components
There are two primary types of React components:
1. Functional Components
Functional components are simpler and preferred for most use cases. They are JavaScript
functions that return React elements. With the introduction of React Hooks, functional components
can also manage state and lifecycle events.
 Stateless or Stateful: Can manage state using React Hooks.
 Simpler Syntax: Ideal for small and reusable components.
 Performance: Generally faster since they don’t require a 'this' keyword.
function Greet(props) {
return <h1>Hello, {[Link]}!</h1>;
}
2. Class Components
Class components are ES6 classes that extend [Link]. They include additional features
like state management and lifecycle methods.
 State Management: State is managed using the [Link] property.
 Lifecycle Methods: Includes methods like componentDidMount,componentDidUpdate, etc.
class Greet extends [Link] {
render() {
return <h1>Hello, {[Link]}!</h1>;
}
}
Props in React Components
Props (short for properties) are read-only inputs passed from a parent component to a child
component. They enable dynamic data flow and reusability.
 Props are immutable.
 They enable communication between components.
function Greet(props) {
return <h2>Welcome, {[Link]}!</h2>;
}

// Usage
<Greet username="Anil" />;
State in React Components
The state is a JavaScript object managed within a component, allowing it to maintain and update its
own data over time. Unlike props, state is mutable and controlled entirely by the component.
 State updates trigger re-renders.
 Functional components use the useState hook to manage state.
function Counter() {
const [count, setCount] = [Link](0);

return (
<div>
<p>Count: {count}</p>
<button onClick={() =>
setCount(count + 1)}>Increment</button>
</div>
);
}
Rendering a Component
Rendering a component refers to displaying it on the browser. React components can be rendered
using the [Link]() method or by embedding them inside other components.
 Ensure the component is imported before rendering.
 The [Link] method is generally used in the root file.
[Link](<Greeting name="Pooja" />, [Link]('root'));
Components in Components
In React, you can nest components inside other components to build a modular and hierarchical
structure.
 Components can be reused multiple times within the same or different components.
 Props can be passed to nested components for dynamic content.
function Header() {
return <h1>Welcome to My Site</h1>;
}

function Footer() {
return <p>© 2024 My Company</p>;
}

function App() {
return (
<div>
<Header />
<p>This is the main content.</p>
<Footer />
</div>
);
}

export default App;


Best Practices for React Components
 Keep Components Small: Each component should do one thing well.
 Use Functional Components: Unless lifecycle methods or error boundaries are required.
 Prop Validation: Use PropTypes to enforce correct prop types.
 State Management: Lift state to the nearest common ancestor when multiple components need
access.

Introduction to TypeScript
TypeScript is a statically typed superset of JavaScript that compiles to plain JavaScript. It adds
features like static typing, interfaces, generics, and modern ECMAScript support, helping developers
catch errors early and build scalable applications with better tooling such as autocompletion,
refactoring, and debugging.
 It is a compiled language, meaning TypeScript code is first converted into JavaScript before
execution.
 Strong typing reduces runtime errors.
 It makes code more predictable, maintainable, and easier to debug.

"Hello, World!" Program in TypeScript


A "Hello, World!" program is the simplest way to get started with any programming language. Here’s
how you can write one using TypeScript.
In Browser (via Compilation)
Create a file [Link]:
// This is our first TypeScript program
let message: string = "Hello, World!";
[Link](message);
Now compile it into JavaScript using:
tsc [Link]
This will generate a [Link] file, which can then be included in your HTML.
<html>
<body>
<h1>Check the console for the message!</h1>
<script src="[Link]"></script>
</body>
</html>
In [Link] Console: Simply run the compiled JavaScript:
node [Link]
Output:
Hello, World!
Comments in JavaScript
Comments are notes in your code that the TypeScript interpreter ignores. They’re great for
explaining what your code does or for testing purposes.
 Single-line comment: Starts with //
// This is a single-line comment
 Multi-line comment: Enclosed in /* */
/* This is a multi-line comment
spanning multiple lines */
Client Side and Server Side Nature of TypeScript
TypeScript’s flexibility extends to both the client-side and server-side, allowing developers to create
complete, scalable applications.
Here’s how it functions in each environment:

Client-Side:
 Used for controlling the browser and its DOM (Document Object Model).
 Handles user events like clicks, form inputs, and rendering dynamic content.
 Common frameworks and libraries like Angular, React, and Vue offer strong TypeScript support for
building large-scale front-end applications.

Server-Side:
 Used for interacting with databases, handling APIs, file manipulation, and generating responses.
 [Link] with TypeScript, along with frameworks like Express or NestJS, is widely used to build type-
safe backend applications.
 Type definitions help catch errors early and make server-side code more reliable and maintainable.
JavaScript Vs TypeScript
JavaScript TypeScript

A lightweight, interpreted scripting language A superset of JavaScript that adds static typing and
used for web development. advanced features.

Dynamically typed (types are checked at Statically typed (optional) – types are checked at compile
runtime). time.

Runs directly in browsers or [Link] (no Must be compiled to JavaScript using the TypeScript
compilation needed). compiler (tsc).

Errors appear only at runtime. Errors are caught at compile time, reducing runtime bugs.

Class-based object-oriented programming with interfaces,


Prototype-based object-oriented programming.
access modifiers, generics.

Supports ES6+ features depending on the Supports all modern ES6+ features, plus extra
environment. TypeScript-only features.

Rich tooling with autocompletion, type checking, and


Basic editor support, limited IntelliSense.
refactoring support.

Used in large-scale applications, compiled to JS for


Runs everywhere (browser, [Link], servers).
execution.

Adding TypeScript File in HTML Code


Here are the steps for adding TypeScript file in html code:
1. Create the TypeScript File ([Link])
let myString;
myString = 'Hello from ts';
[Link](myString);
 myString is declared as a string variable.
 It's assigned the value 'Hello from TypeScript'.
 The value is logged to the console.
2. Compile TypeScript to JavaScript
Use the TypeScript compiler (tsc) to transpile [Link] into JavaScript. Open your terminal and run:
tsc [Link]
This command generates a [Link] file containing the equivalent JavaScript code.
3. Create the HTML File ([Link])
<html lang="en">
<head>
</head>
<body>
<h2>Welcome to GeeksforGeeks</h2>
<p>Default code has been loaded into the Editor.</p>
<script src="[Link]"></script>
</body>
</html>
 A heading and a paragraph for content.
 A script tag that references the compiled JavaScript file [Link].
4. Run the HTML File
Open [Link] in a web browser.
Limitations of TypeScript
Despite its power, TypeScript has some limitations to consider:
 Compilation Overhead: Must be compiled into JavaScript before execution.
 Learning Curve: Developers must learn types, generics, and advanced concepts.
 Configuration Complexity: Large projects may require detailed [Link] setup.
 Extra Build Step: Slower feedback loop compared to plain JavaScript.

How to Pass Data from One Component to Another Component in ReactJS?


In ReactJS, components are the building blocks of your user interface. Components allow you to
create modular, reusable UI elements, but sometimes these components need to communicate with each
other.
we will explore the different methods to pass data between components in ReactJS.
1. Passing data from Parent to Child in React
The most common way to pass data between components is through props (short for properties). Props are
read-only and allow you to pass information from a parent component to its child components. When you
define a child component, you can pass it data by setting its props.
2. Passing data from Child to Parent Component
In React, data usually flows from parent to child through props. But what if you need to pass data from a
child component back to the parent? To achieve this, you can pass a callback function from the parent to the
child. When the child component needs to send data to the parent, it calls this function with the data.
3. Passing Data Between Sibling Components
When you need to pass data between sibling components (components that share the same parent), the best
way is to use their common parent component as a mediator. The parent component can manage the shared
state and pass it down to both child components.
Module 4
Express/Node introduction
Introducing Node
Node (or more formally [Link]) is an open-source, cross-platform runtime environment that allows
developers to create all kinds of server-side tools and applications in JavaScript. The runtime is intended for
use outside of a browser context (i.e., running directly on a computer or server OS). As such, the
environment omits browser-specific JavaScript APIs and adds support for more traditional OS APIs
including HTTP and file system libraries.
From a web server development perspective Node has a number of benefits:
 Great performance! Node was designed to optimize throughput and scalability in web applications and is a
good solution for many common web-development problems (e.g., real-time web applications).
 Code is written in "plain old JavaScript", which means that less time is spent dealing with "context shift"
between languages when you're writing both client-side and server-side code.
 JavaScript is a relatively new programming language and benefits from improvements in language design
when compared to other traditional web-server languages (e.g., Python, PHP, etc.) Many other new and
popular languages compile/convert into JavaScript so you can also use TypeScript, CoffeeScript,
ClojureScript, Scala, LiveScript, etc.
 The node package manager (npm) provides access to hundreds of thousands of reusable packages. It also has
best-in-class dependency resolution and can also be used to automate most of the build toolchain.
 [Link] is portable. It is available on Microsoft Windows, macOS, Linux, Solaris, FreeBSD, OpenBSD,
WebOS, and NonStop OS. Furthermore, it is well-supported by many web hosting providers, that often
provide specific infrastructure and documentation for hosting Node sites.
 It has a very active third party ecosystem and developer community, with lots of people who are willing to
help.
You can use [Link] to create a simple web server using the Node HTTP package.
Hello [Link]
The following example creates a web server that listens for any kind of HTTP request on the
URL [Link] — when a request is received, the script will respond with the string: "Hello
World". If you have already installed node, you can follow these steps to try out the example:
1. Open Terminal (on Windows, open the command line utility)
2. Create the folder where you want to save the program, for example, test-node and then enter it by
entering the following command into your terminal:
BASHCopy
cd test-node
3. Using your favorite text editor, create a file called [Link] and paste the following code into it:
JSCopy
// Load HTTP module
const http = require("http");
const hostname = "[Link]";
const port = 8000;
// Create HTTP server
const server = [Link]((req, res) => {
// Set the response HTTP header with HTTP status and Content type
[Link](200, { "Content-Type": "text/plain" });
// Send the response body "Hello World"
[Link]("Hello World\n");
});
// Prints a log once the server starts listening
[Link](port, hostname, () => {
[Link](`Server running at [Link]
});

4. Save the file in the folder you created above.


5. Go back to the terminal and type the following command:
node [Link]
Web Frameworks
Other common web-development tasks are not directly supported by Node itself. If you want to add specific
handling for different HTTP verbs (e.g., GET, POST, DELETE, etc.), separately handle requests at different
URL paths ("routes"), serve static files, or use templates to dynamically create the response, Node won't be
of much use on its own. You will either need to write the code yourself, or you can avoid reinventing the
wheel and use a web framework!
Introducing Express
Express is the most popular [Link] web framework, and is the underlying library for a number of other popular
[Link] frameworks. It provides mechanisms to:
 Write handlers for requests with different HTTP verbs at different URL paths (routes).
 Integrate with "view" rendering engines in order to generate responses by inserting data into templates.
 Set common web application settings like the port to use for connecting, and the location of templates that are used
for rendering the response.
 Add additional request processing "middleware" at any point within the request handling pipeline.
While Express itself is fairly minimalist, developers have created compatible middleware packages to address almost
any web development problem. There are libraries to work with cookies, sessions, user logins, URL
parameters, POST data, security headers, and many more. You can find a list of middleware packages maintained by
the Express team at Express Middleware (along with a list of some popular 3rd party packages).
Is Express opinionated?
Web frameworks often refer to themselves as "opinionated" or "unopinionated".
Opinionated frameworks are those with opinions about the "right way" to handle any particular task. They
often support rapid development in a particular domain (solving problems of a particular type) because the
right way to do anything is usually well-understood and well-documented. However they can be less flexible
at solving problems outside their main domain, and tend to offer fewer choices for what components and
approaches they can use.
Unopinionated frameworks, by contrast, have far fewer restrictions on the best way to glue components
together to achieve a goal, or even what components should be used. They make it easier for developers to
use the most suitable tools to complete a particular task, albeit at the cost that you need to find those
components yourself.
Express is unopinionated. You can insert almost any compatible middleware you like into the request
handling chain, in almost any order you like. You can structure the app in one file or multiple files, and
using any directory structure. You may sometimes feel that you have too many choices!
What does Express code look like?
In a traditional data-driven website, a web application waits for HTTP requests from the web browser (or
other client). When a request is received the application works out what action is needed based on the URL
pattern and possibly associated information contained in POST data or GET data. Depending on what is
required it may then read or write information from a database or perform other tasks required to satisfy the
request. The application will then return a response to the web browser, often dynamically creating an
HTML page for the browser to display by inserting the retrieved data into placeholders in an HTML
template.
Express provides methods to specify what function is called for a particular HTTP verb (GET, POST, PUT,
etc.) and URL pattern ("Route"), and methods to specify what template ("view") engine is used, where
template files are located, and what template to use to render a response. You can use Express middleware to
add support for cookies, sessions, and users, getting POST/GET parameters, etc. You can use any database
mechanism supported by Node (Express does not define any database-related behavior).
The following sections explain some of the common things you'll see when working
with Express and Node code.
Helloworld Express
First lets consider the standard Express Hello World example (we discuss each part of this below, and in the
following sections).
const express = require("express");

const app = express();


const port = 3000;
[Link]("/", (req, res) => {
[Link]("Hello World!");
});

[Link](port, () => {
[Link](`Example app listening on port ${port}!`);
});

The first two lines require() (import) the express module and create an Express application. This object,
which is traditionally named app, has methods for routing HTTP requests, configuring middleware,
rendering HTML views, registering a template engine, and modifying application settings that control how
the application behaves (e.g., the environment mode, whether route definitions are case sensitive, etc.)
The middle part of the code (the three lines starting with [Link]) shows a route definition.
The [Link]() method specifies a callback function that will be invoked whenever there is an
HTTP GET request with a path ('/') relative to the site root. The callback function takes a request and a
response object as arguments, and calls send() on the response to return the string "Hello World!"
The final block starts up the server on a specified port ('3000') and prints a log comment to the console. With
the server running, you could go to localhost:3000 in your browser to see the example response returned.

Importing and creating modules


A module is a JavaScript library/file that you can import into other code using
Node's require() function. Express itself is a module, as are the middleware and database libraries that we
use in our Express applications.
The code below shows how we import a module by name, using the Express framework as an example. First
we invoke the require() function, specifying the name of the module as a string ('express'), and calling the
returned object to create an Express application. We can then access the properties and functions of the
application object.
const express = require("express");

const app = express();

To make objects available outside of a module you just need to expose them as additional properties on
the exports object. For example, the [Link] module below is a file that exports area() and perimeter() methods:
[Link] = function (width) {
return width * width;
};
[Link] = function (width) {
return 4 * width;
};

Using asynchronous APIs


JavaScript code frequently uses asynchronous rather than synchronous APIs for operations that may take
some time to complete. A synchronous API is one in which each operation must complete before the next
operation can start. For example, the following log functions are synchronous, and will print the text to the
console in order (First, Second).

[Link]("First");

[Link]("Second");

By contrast, an asynchronous API is one in which the API will start an operation and immediately return (before the
operation is complete). Once the operation finishes, the API will use some mechanism to perform additional
operations. For example, the code below will print out "Second, First" because even though setTimeout() method
is called first, and returns immediately, the operation doesn't complete for several seconds.
setTimeout(() => {

[Link]("First");

}, 3000);

[Link]("Second");

Using non-blocking asynchronous APIs is even more important on Node than in the browser
because Node applications are often written as a single-threaded event-driven execution environment.
"Single threaded" means that all requests to the server are run on the same thread (rather than being spawned
off into separate processes). This model is extremely efficient in terms of speed and server resources.
However, it does mean that if any of your functions call synchronous methods that take a long time to
complete, they will block not only the current request, but every other request being handled by your web
application.
There are multiple ways for an asynchronous API to notify your application that it has completed.
Historically, the approach used was to register a callback function when invoking the asynchronous API,
which is then called when the operation completes

Vital for developing modern web applications


Developing modern web apps requires a blend of user-centric design, robust tech stacks (JS, React/Vue/ Angular,
Node/Python backends), microservices, cloud deployment, and DevOps (CI/CD, Docker, K8s) for scalability and
security, focusing on responsive design, performance, accessibility, and maintainability to meet high user expectations
for speed and seamless experience across devices.
Core Principles & Practices
 User-Centric Design (UCD): Intuitive, accessible, and engaging experiences.
 Responsive Design: Adapts to any screen size (mobile-first approach recommended).
 Security by Design: Built-in security from the start, not an add-on.
 Performance Optimization: Fast loading, efficient data handling (caching, DB optimization).
 Maintainability: Modular, reusable code, version control, following standards.
Key Technologies & Architectures
 Frontend: HTML, CSS, JavaScript (Frameworks: React, Angular, Vue, Svelte).
 Backend: [Link], Python (Django/Flask), Java, PHP.
 APIs: RESTful or GraphQL for communication.
 Microservices: Loosely coupled services for flexibility and scale.
 Databases: SQL (Postgres, MySQL) or NoSQL (MongoDB).
Infrastructure & Delivery
 Cloud-Native: Leveraging AWS, Azure, GCP for scalability.
 DevOps: CI/CD pipelines (Jenkins, GitHub Actions) for automation.
 Containerization: Docker & Kubernetes for deployment.
 Progressive Web Apps (PWAs): Web apps with native-like features.
Essential Tools
 Version Control: Git/GitHub.
 Monitoring: Sentry, Logstash for errors/logs.
 Caching: Redis, Memcached.
Creating REST APIs, and performing CRUD operations
JavaScript techniques like asynchronous callbacks and Promises, creating REST APIs, and performing fundamental
CRUD (Create, Read, Update, Delete) operations. These are core skills for a backend developer.
To achieve these goals, you'll likely be working with:
 [Link] and [Link]: The standard stack for building server-side applications and REST APIs in
JavaScript.
 Databases:
o NoSQL (like MongoDB): Often used with an Object Data Modeling (ODM) library like Mongoose for
efficient data handling.
o SQL (like PostgreSQL or MySQL): Used with libraries like Sequelize or [Link] for relational data
management.
 Asynchronous Handling: Implementing callbacks for simple events, and promises (often
utilizing async/await syntax for cleaner code) to manage complex sequences of operations like database queries or
external API calls.

Callbacks vs Promises vs Async/Await


Handling asynchronous operations is an essential part of JavaScript programming, especially when
dealing with APIs, file handling, database queries, and user interactions. JavaScript provides three
main ways to manage asynchronous tasks:
 Callbacks: The traditional approach using functions passed as arguments.
 Promises: A better alternative that improves readability and avoids callback nesting.
 Async/Await: A modern and cleaner syntax that makes asynchronous code look synchronous.
Callbacks vs Promises vs Async/Await
Feature Callbacks Promises Async/Await

Objects representing Syntactic sugar over


Functions passed as
eventual completion or failure Promises, using async
arguments to other
of an asynchronous functions and await
functions.
Definition operation. expressions.

Can lead to "callback hell" Allows chaining with .then() Provides a more synchronous-
with nested functions, and .catch(), improving like flow, enhancing
Readability making code hard to read. readability. readability.

Requires manual checks Errors are handled using


Error Utilizes try...catch blocks,
and can be cumbersome in .catch(), centralizing error
simplifying error handling.
Handling nested callbacks. management.

Enables writing asynchronous


Sequential execution, but Supports chaining, allowing
code in a synchronous
complex flows can become for more manageable control
manner, simplifying control
difficult to manage. flows.
Control Flow flow.

Supported in ES2017 and


Supported in all JavaScript Supported in all modern
later; may require transpilation
environments. JavaScript environments.
Support for older environments.

Similar to Promises; may have


Minimal overhead; direct Slight overhead due to
slight overhead but generally
function calls. Promise object creation.
Performance negligible.

What is Callback?
Callbacks are functions passed as arguments to other functions and are executed once a specific
task is completed. They are commonly used in JavaScript for handling asynchronous operations but
can lead to "callback hell" when nested multiple times.
// Callback function to process user data
function process(data, callback) {
[Link]("Processing user data:", data);
callback();
}

// Function to fetch user data with a callback


function fetch(callback) {
// Simulating an API request
const user = { id: 1, name: "Pushkar" };
callback(user);
}
// Using the callback
fetch((data) => {
process(data, () => {
[Link]("User data processed successfully.");
});
});

Output
Processing user data: { id: 1, name: 'Pushkar' }
User data processed successfully.
In this example
 Callbacks are passed as arguments to other functions.
 They execute once the asynchronous operation is completed.
 Callback hell can occur with multiple nested callbacks, making the code harder to read and
maintain.
What is Promises?
Promises offer a more structured approach to handle asynchronous operations, addressing the
callback hell problem. They represent the eventual completion (or failure) of an asynchronous task.
//Function to fetch user data with a Promise
function fetch() {
// Simulating an API request
const user = { id: 1, name: "Pushkar" };

return new Promise((resolve, reject) => {


if (user) {
resolve(user);
} else {
reject("Error fetching user data.");
}
});
}

// Using the Promise


fetch()
.then((data) => {
[Link]("Processing user data:", data);
[Link]("User data processed successfully.");
})
.catch((error) => {
[Link]("Error:", error);
});

Output
Processing user data: { id: 1, name: 'Pushkar' }
User data processed successfully.
In this example
 Promises represent the completion of an asynchronous task.
 They are chained with .then() for successful completion and .catch() for errors.
 Promises improve readability compared to callbacks, preventing nested structures.
What is Async/Await?
Async/Await is built on top of Promises and allows asynchronous code to be written in a
synchronous style, making it easier to read and understand.
// Function to fetch user data with Async/Await
async function fetch() {
// Simulating an API request
const user = { id: 1, name: "Pushkar" };

return new Promise((resolve) => {


resolve(user);
});
}

// Function to process user data using Async/Await


async function process() {
try {
const data = await fetch();
[Link]("Processing user data:", data);
[Link]("User data processed successfully.");
} catch (error) {
[Link]("Error:", error);
}
}

// Using Async/Await
process();

Output
Processing user data: { id: 1, name: 'Pushkar' }
User data processed successfully.
In this example
 Async/Await simplifies asynchronous code, making it appear synchronous.
 The await keyword pauses the execution until the Promise is resolved.
 Async/Await is ideal for handling multiple asynchronous operations in a clear, easy-to-read way.
When to Use Callbacks
Callbacks are suitable for simple asynchronous operations where you only need to handle one or
two asynchronous tasks. They are the original way to handle asynchronous code in JavaScript.
 Simple Asynchronous Tasks: When you have a single asynchronous operation to perform,
callbacks can be straightforward.
 Legacy Code: You might encounter callbacks in older JavaScript codebases or libraries.
When to Use Promises
Promises are a better choice for managing more complex asynchronous code, especially when you
have multiple operations that depend on each other.
 Chaining Asynchronous Operations: Promises excel when you need to execute asynchronous
tasks sequentially.
 Improved Error Handling: Promises provide a cleaner way to handle errors compared to
callbacks.
 Modern JavaScript APIs: Many modern JavaScript APIs and libraries are promise-based.
When to Use Async/Await
async/await is generally the preferred way to work with asynchronous code in modern JavaScript. It
makes asynchronous code look and behave a bit more like synchronous code.
 Readability and Maintainability: async/await significantly improves the readability of complex
asynchronous code.
 Simplified Control Flow: async/await allows you to use familiar control flow structures (like if
statements and loops) within your asynchronous code.
 Working with Promises: async/await is built on top of promises, so it works seamlessly with
promise-based APIs. It's generally the best approach when dealing with promises.
Creating REST APIs that perform CRUD operations is a fundamental concept in web development. CRUD stands
for Create, Read, Update, and Delete, the four basic functions for managing data in any application. REST
(Representational State Transfer) is an architectural style that maps these operations to standard HTTP methods.
Mapping CRUD to HTTP Methods
In a REST API, each CRUD operation corresponds to a specific HTTP method, which provides a uniform interface for
client-server interaction.
CRUD Description HTTP Method Typical URL Endpoint Typical
Operation (Resource: users ) Success
Status Code
Create Add new POST /users 201 (Created)
resources to
the database.

Read Retrieve GET /users (all) 200 (OK)


resources or or /users/:id (single)
collections of
resources.

Update Modify existing PUT (full update) /users/:id 200 (OK)


resources. / PATCH (partial or 204 (No
update) Content)

Delete Remove DELETE /users/:id 204 (No


resources from Content)
the database.

Key Principles for Building RESTful CRUD APIs


 Resource-Oriented URLs: Use clear, noun-based URLs (e.g., /products instead of /getProducts ) to
describe the resource.
 Use Proper HTTP Status Codes: Return appropriate HTTP status codes (e.g., 404 Not Found for a missing
resource, 400 Bad Request for invalid input) to indicate the result of the operation.
 Statelessness: Each request should be independent and contain all the necessary information, without
relying on the server remembering previous interactions.
 Data Format: Modern REST APIs typically use JSON (JavaScript Object Notation) for data exchange due to
its lightweight and readable nature.
 Security: Implement authentication (e.g., OAuth 2.0, JWT) and authorization mechanisms to ensure only
authorized users can perform operations.
Tools for Development and Testing
 Backend Frameworks: Use frameworks like [Link] ([Link]), Spring Boot (Java), or FastAPI (Python) to
streamline API development.
 Databases: A database (e.g., MongoDB, PostgreSQL, MySQL) is needed to store and manage your data.
 API Testing Tools: Tools like Postman or Insomnia allow you to easily send HTTP requests to your API
endpoints and inspect the responses.
 Documentation Tools: Use standards like OpenAPI (formerly Swagger) to document your API's capabilities
and generate interactive documentation for other developers.
REST API Introduction
REST API stands for Representational State Transfer API. It is a type of API (Application Programming
Interface) that allows communication between different systems over the internet. REST APIs work by
sending requests and receiving responses, typically in JSON format, between the client and server.
 A request is sent from the client to the server via a web URL, using one of the HTTP methods.
 The server then responds with the requested resource, which could be HTML, XML, Image, or
JSON, with JSON being the most commonly used format for modern web services.
 These methods map to CRUD operations (Create, Read, Update, Delete) for managing resources
on the web.
Common HTTP Methods Used in REST API
In HTTP, there are five methods that are commonly used in a REST-based Architecture, i.e., POST,
GET, PUT, PATCH, and DELETE. These correspond to create, read, update, and delete (or CRUD)
operations, respectively. There are other methods that are less frequently used, like OPTIONS and
HEAD.
1. GET Method
The HTTP GET method is used to read (or retrieve) a representation of a resource. In the safe path,
GET returns a representation in XML or JSON and an HTTP response code of 200 (OK). In an error
case, it most often returns a 404 (NOT FOUND) or 400 (BAD REQUEST).
GET /users/123
This request fetches data for the user with ID 123.
2. POST Method
The POST method is commonly used to create new resources. It is often used to create subordinate
resources related to a parent resource. Upon successful creation, the server returns HTTP status
201 (Created) along with a Location header pointing to the newly created resource.
POST /users
{
"name": "Anjali",
"email": "gfg@[Link]"
}
This request creates a new user with the given data.
3. PUT Method
PUT is an HTTP method used to update or create a resource on the server. When using PUT, the
entire resource is sent in the request body, and it replaces the current resource at the specified URL.
If the resource doesn’t exist, it can create a new one.
PUT /users/123
{
"name": "Anjali",
"email": "gfg@[Link]"
}
This request updates the user with ID 123 or creates a new user if one doesn't exist.
4. PATCH Method
PATCH is an HTTP method used to partially update a resource on the server. Unlike PUT, PATCH
only requires the fields that need to be updated to be sent in the request body. It modifies specific
parts of the resource rather than replacing the entire resource.
PATCH /users/123
{
"email": "[Link]@[Link]"
}
5. DELETE Method
It is used to delete a resource identified by a URI. On successful deletion, return HTTP status 200
(OK) along with a response body.
DELETE /users/123
This request deletes the user with ID 123.
Building a Simple REST API using [Link] and Express
Now let's create a REST AP and perform the various HTTP operations.
Step 1: Create the folder
Create the NodeJs project by using the following command:
mkdir node-app
cd node-app
Step 2: Install the [Link]
npm init –y
Step 3: Install Express
To begin building a REST API in [Link], you need to install Express. Run the following command in your
terminal:
npm install express
Step 4: Create the Server
Here’s a basic example of creating a REST API in [Link] using Express
// Import the Express module
const express = require('express');
const app = express();
const port = 3000;
[Link]([Link]());
// Define a route for GET requests
[Link]('/users', (req, res) => {
[Link]({ message: 'Returning list of users' });
});
// Define a route for POST requests
[Link]('/users', (req, res) => {
const newUser = [Link];
[Link]({ message: 'User created', user: newUser });
});
// Define a route for PUT requests
[Link]('/users/:id', (req, res) => {
const userId = [Link];
const updatedUser = [Link];
[Link]({ message: `User with ID ${userId} updated`, updatedUser });
});
// Define a route for DELETE requests
[Link]('/users/:id', (req, res) => {
const userId = [Link];
[Link]({ message: `User with ID ${userId} deleted` });
});
// Start the server
[Link](port, () => {
[Link](`Server is running on [Link]
});

Features of REST APIs


 Stateless: Each request from a client to a server must contain all the information the server
needs to fulfill the request. No session state is stored on the server.
 Client-Server Architecture: RESTful APIs are based on a client-server model, where the client
and server operate independently, allowing scalability.
 Cacheable: Responses from the server can be explicitly marked as cacheable or non-cacheable
to improve performance.
 Uniform Interface: REST APIs follow a set of conventions and constraints, such as consistent
URL paths, standardized HTTP methods, and status codes, to ensure smooth communication.
 Layered System: REST APIs can be deployed on multiple layers, which helps with scalability and
security.

Real world Example of Rest APIs :


REST APIs are widely used across various industries to simplify communication between systems.
Some common applications include:
 Social Media: Integrating third-party platforms like Facebook, Twitter, and Instagram for features
like login, sharing, and posting.
 E-Commerce: Managing products, processing payments, handling orders, and customer
management.
 Geolocation Services: GPS tracking, real-time location updates, and location-based services like
finding nearby places.
 Weather Forecasting: Fetching weather data from external sources to provide real-time weather
updates and forecasts.

You might also like