0% found this document useful (0 votes)
18 views123 pages

Final - PPT 2

The document outlines a comprehensive curriculum for HTML5 and JavaScript, detailing various experiments and concepts related to web development. It covers fundamental topics such as HTML structure, elements, attributes, and JavaScript programming, including asynchronous programming and Node.js. Each section includes syntax examples and explanations of key concepts, aimed at providing a foundational understanding of web technologies.

Uploaded by

Harshini Ryali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views123 pages

Final - PPT 2

The document outlines a comprehensive curriculum for HTML5 and JavaScript, detailing various experiments and concepts related to web development. It covers fundamental topics such as HTML structure, elements, attributes, and JavaScript programming, including asynchronous programming and Node.js. Each section includes syntax examples and explanations of key concepts, aimed at providing a foundational understanding of web technologies.

Uploaded by

Harshini Ryali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 123

INDEX

S. NO. Date Name of the experiment page No Marks Awarded Remarks

1a Case-insensitivity,Platform-independency
DOCTYPE Declaration, Types of Elements
HTML Elements - Attributes, Metadata Element
1b Sectioning Elements
1c Paragraph Element, Division and Span
Elements, List Element
1d Link Element
1e Character Entities
1f HTML5 Global Attributes
2a Creating Table Elements, Table Elements :
Colspan/Rowspan Attributes, border, cellspacing,
cellpadding attributes Enhance the details
page of IEKart's Shopping application by
adding a table element to display the available
mobile/any inventories.
2b Creating Form Elements, Color and Date Pickers,
Select and Datalist Elements
2c Input Elements - Attributes
2d Media, Iframe
3a Type of Identifiers
3b Primitive and Non Primitive Data Types
3c Operators and Types of Operators
3d Types of Statements, Non - Conditional
Statements, Types of Conditional Statements,
if Statements,switch Statements
4a Types of Loops
Types of Functions, Declaring and Invoking
Function, Arrow Function, Function Parameters,
Nested Function, Built-in Functions, Variable
Scope in Functions
4b Working With Classes, Creating and
Inheriting Classes
4c In-built Events and Handlers
4d Working with Objects, Types of Objects,
Creating Objects, Combining and cloning
Objects using Spread operator, Destructuring
Objects, Browser Object Model, Document
Object Mode
5a Creating Arrays, Destructuring Arrays,
Accessing Arrays, Array Methods
5b Introduction to Asynchronous Programming,
Callbacks, Promises, Async and Await,
Executing Network Requests using Fetch API
5c Creating Modules, Consuming Modules
6a How to use Node.js
6b Create a web server in Node.js
6c Modular programming in Node.js
6d Restarting Node Application
6e File Operations
7a Defining a route, Handling Routes, Route
Parameters, Query Parameters
7b How Middleware works, Chaining of
Middlewares, Types of Middlewares
7c Connecting to MongoDB with Mongoose,
Validation Types and Defaults
7d Models
8a CRUD Operations
8b API Development
8c Why Session management, Cookies
8d Sessions
8e Why and What Security, Helmet Middleware
9a Basics of TypeScript
9b Function
9c Parameter Types and Return Types
9d Arrow Function
9e Optional and Default Parameters
10a Rest Parameter
10b Creating an Interface
10c Duck Typing
10d Function Types
11a Extending Interfaces
11b Classes
11c Constructor
11d Access Modifiers
12a Properties and Methods
12b Creating and using Namespace
12c Creating and using Modules
12d What is Generics, What are Type Parameters,
Generic Functions, Generic Constraints

COURSE NAME : HTML 5 – THE LANGUAGE


EXPERIMENT-1 :
1a) INTRODUCTION TO HTML-5 :
WHAT IS HTML?

Hyper Text Markup Language (HTML) is a standard markup language to create the
structure of a web page. It annotates the content on a web page using HTML elements.
In a web page, all instructions to the browser are given in the form of HTML tags, also known as
HTML elements.
The basic structure of html is:
<!DOCTYPE html>
<html>
<head>
<title> Homepage </title>
</head>
<body>
//paragraph
</body>

</html>

Case-insensitivity :
HTML elements are case-insensitive. The browser understands the
HTML tags irrespective of their cases.
Syntax:
<!DOCTYPE html>
<html>
<head>
<title>Homepage </title> </head>
<body> Hello
World!
</boDy>
</html>

OUTPUT: Hello World!

PLATFORM-INDEPENDENCY:HTML Language is platform-independent. That means the same


HTML code can run on different operating systems as shown below.

Syntax:

<!DOCTYPE html>
<html>
<head>
<title>sample page</title>
</head>
<body>
<p>Hello World!</p>
</body> </html>
Output:

Doctype Declaration :
There are many versions of HTML out there such as HTML 2.0, HTML 3.0, HTML 3.2,
HTML4.0, HTML 4.01 and latest is HTML5.0. In each version, some elements and attributes are
either added or depreciated. The appearance of your .html page depends on how the browser
renders HTML elements. And how the browser renders HTML elements depends on how the

browser understands them.

Types of Elements:
HTML elements can be further categorized into two as below: Block Element:
A block element begins on a new line occupying the entire width of the parent tag.
Inline Element: An inline element occupies the necessary space to accommodate the content in the
element. Inline elements can be nested within other inline elements, whereas, block elements
cannot be nested within inline elements.
Html Elements-Attributes, metadata elements:
HTML elements can contain attributes that can be considered as an additional feature to set
various properties and they are optional. Some of the attributes can be used with any of the HTML
elements and there can be referred to as ‘global attributes’. Also, some attributes can be used only
with particular elements. Following are some features of attributes:

The lang attribute specifies the language of the content of the HTML page.
Metadata:
The <meta> tag defines metadata about an HTML document. Metadata is data (information) about
data.
<meta> tags always go inside the <head> element, and are typically used to specify character set,
page description, keywords, author of the document, and viewport settings.
Syntax:
<meta name="viewport" content="width=device-width, initial-scale=1.0">

1b) Sectioning Elements:


Web crawlers like Google, Bing, etc. are widely used for searching websites. They lookup each
web page code and render the web page as per the HTML tags used and the styling associated.
Any regular user who is accessing any website will notice the below observations in most of the
web pages of the website:
1. Right at the beginning of a web page, a header containing the website name is clearly
displayed in the form of a logo or text. This helps the user to know which website they are
currently referring to.
2. The links to navigate to other web pages of the website are displayed in the header. This
makes a website user to figure out easily how to access other web pages of that website.
3. Details like copyright, about us, etc. are usually displayed at the bottom end of the screen,
as part of the footer, as these details hold lesser importance, as compared to the actual data
that they intend to read in the page.
<header>
The <header> element is used to include header content like web page logo, login link, website
settings link, etc. Ideally, every web page has one header. However, multiple headers may also be
included as per need.
Syntax:
<header>
<h3>About Us</h3>
</header>
<footer>
The <footer> element is used to include footer content like copyright, about us, terms and
conditions link, etc. One footer is included per page.
Syntax:
<footer>
Copyright @ WayFar, 2020
<a href="./AboutUs.html">About Us</a>
</footer>
<main>
The <main> element is used for demarking the main content of the web page. Only one main tag
per web page is allowed.
Syntax:
<main> <section>
..
</section>
<section> <article>
..
</article>
<article>
..
</article>
</section>
</main>
<nav>
The <nav> element is used for navigational content like navigation menu for the website. There is
no limit to the number of times <nav> tag can be used on a web page. As long as there are
navigation links, links can be wrapped inside <nav>.
Syntax:
<nav>
<a href="Home.html">Home</a>
<a href="Login.html">Login</a>
</nav>
<section>
The <section> element is used to organize the web page into different sections.
Syntax:
<main>
<section>
<p>Section 1</p>
</section>
<section>
<p>Section2</p>
</section> </main> <article>:
The <article> element is used to include self-contained composition on a web page. Syntax:
<article>
<h1>MEAN stack</h1>
<p>MEAN stack training includes discussion on MongoDB,Node,
Express and Angular with the corresponding certifications</p>
</article>

1c) Paragraph Element:


The paragraph element is generally used for denoting a paragraph. Any textual content can be
mentioned inside this element.
It is defined using <p>…</p> tag.
Syntax:
<!DOCTYPE html>
<html>
<body>
<p>This is a Paragraph</p>
</body>
</html>
Division Elements:
The division element is used to group various other HTML tags. This element helps us in
organizing the web page into different sections.
If any common rule or style needs to be added to a particular section, the same can be applied to
the corresponding division. The rule or style gets applied to all the contents of the division
thereby.It is defined using <div>…</div> tag.
Syntax:
<!DOCTYPE html>
<html>
<body>
<div>
<p> This is first paragraph </p>
<p> This is second paragraph </p>
<p> This is third paragraph </p>
</div>
</body>
</html>
Span Element:
Similar to the division element, the span element is also used to group various other HTML tags
to apply some common styles.It is defined by using <span> ...</span> tag.
The span element is by default inline in nature, and hence no new line is added after the span
ends. This tag is preferred only when we cannot use any other semantic tags.
Syntax:
<!DOCTYPE html>
<html>
<body>
<div>
<span>first section of paragraph</span>
<span>second section of paragraph</span> </div>
</body>
</html>
List Element:
HTML Lists are used to specify lists of information. All lists may contain one or more list
elements. There are three different types of HTML lists:

1. Ordered List or Numbered List (ol)


2. Unordered List or Bulleted List (ul)
3. Description List or Definition List (dl)

Ordered List or Numbered list :


In the ordered HTML lists, all the list items are marked with numbers by default. It is
known as numbered list also. The ordered list starts with <ol> tag and the list items start
with <li> tag.

Syntax:

<h1>Courses offered:</h1>

<ol>
<li>HTML5</li>

<li>CSS</li>

<li>JS</li>

<li>Bootstrap</li>

</ol>

Unordered list or bulleted list:


In HTML Unordered list, all the list items are marked with bullets. It is also known as
bulleted list also. The Unordered list starts with <ul> tag and list items start with the <li> tag.
Syntax:
<h1>Courses offered:</h1>
<ul style="list-style-type: square;">
<li>HTML5</li>
<li>CSS</li>
<li>JS</li>
<li>Bootstrap</li>
</ul>

Description list or Definition list:

HTML Description list is also a list style which is supported by HTML and XHTML. It is also
known as definition list where entries are listed like a dictionary or encyclopedia.

The HTML definition list contains following three tags:

1. <dl> tag defines the start of the list.


2. <dt> tag defines a term.
3. <dd> tag defines the term definition (description).

Syntax:
<dl>
<dt> Description Term 1 </dt>
<dd> Description Definition 1 </dd>
<dt> Description Term 2 </dt>
<dd> Description Definition 2 </dd> </dl>
1d) Link Element:
A website necessarily is a collection of related web pages, where each web page is typically
created for a particular purpose.
When developing any website:
● Each web page is necessarily coded in individual HTML files.
● To see a particular web page, the respective HTML file has to be opened up in a browser.
Below are the advantages if hyperlinks are used:
● We can create connections or links between HTML documents/web
pages and users can navigate from one web page to another by clicking on "hyperlinks".
● We would now feel that we have a website which is a collection of interconnected web
pages.
Link elements are defined using <a> .. </a> tag as below:

A hyperlink is a prime way in which users can navigate from one web page to another. A
hyperlink can point to another web page, or website, or files, or even specific locations on the
same web page.Hyperlinks can be of any of the below types:

Text hyperlink:
● A clickable text is used to take the user to another web page.Largely, we use text-based
hyperlinks.
● This text usually appears with an underline and in a different color.
● This color mapping is automatically done by the browser for all text hyperlinks.

Syntax:
<a href="Enquire.html"> Click here to connect to us </a><br/>

<a href="http://www.google.com"> Click here to go to Google website </a>

Image hyperlink:
● A clickable image is used to take the user to another web page.
Syntax:

<a href="http://www.google.com">
<img src="google.jpg" />
</a>
Bookmark hyperlink:
When a web page is lengthy, we commonly come across icons or links that say "Go to Top" or
"Go to Bottom". Click on these links does take the user to the top of the page or bottom, as
applicable. Sometimes we also observe, on click of a text in the menu bar, the page auto scrolls to
that particular section on that page. This is achieved by using the Bookmarking concept and the
same is implemented by using hyperlinks.
Syntax:
<h2 id="top">Topic</h2>
<p>Detail……</p>
<p>Detail……</p>
<p>Detail……</p>
<a href="#top">Go to Top</a>
Email hyperlink:
● It allows users to send an email by clicking on that link.
Syntax:
<a href="mailto:[email protected]?Subject=Hello%20again">Sen d Mail</a>
Contact number hyperlink:
● It allows the user to call a number by clicking on that link.
Let us discuss various hyperlinks that can be created in an HTML page.
Syntax:
<a href="tel:+9999">Call Us</a>

1e) Character Entities:


Some characters are reserved in HTML.
For example: If you use the less than (<) or greater than (>) sign in your content, the browser may
mix them with HTML tags.
Also, some characters are unavailable on the keyboard.
For example:
©Character entities are used to include such character content on a web page.

The table below lists widely used character entities supported in HTML5.

CHARACTER DESCRIPTION ENTITY NAME ENTITY NUMBER

&nbsp; &#160;
Non-breaking space
< Less than &lt; &#60;
> Greater than &gt; &#62
& Ampersand &amp &#38;
© Copyright &copy; &#169;
€ Euro &euro &#8364;

£ Pound &pound; &#163;


® Registered trademar &reg; &#174;

1f) HTML5 Global Attributes:


HTML global attributes are those attributes which are common for all HTML elements. The
global attributes are supported by both standard and non-standard element.
The global attributes can be used with all elements, although it may not have any effect on some
elements.

Attribute Description
contenteditable Allows the user to edit content. Possible values are true/false.
dir Specifies text direction. Possible values are Itr/ rtl.
title Displays the string message as a tooltip.
Specifies whether the spelling of an element's value should be checked
spellcheck
or not. Possible values are true/false.
id Gives a unique id to an element.

EXPERIMENT-2
COURSE NAME: JAVASCRIPT
A. CREATING TABLE ELEMENTS
HTML Tables provide a means by which we can create a tabular format
of data on the web.
1.The table element is defined in HTML using <table>...</table> tag It contains
table header and table body.
2.The table header is for adding header information like column headers and the
table body is for table contents.

The <caption> tag defines a table caption.The <caption> tag must be inserted
immediately after the <table> tag.

The following elements are used within the table element:

Col span and Row span Attributes:


The elements < td > and < th> supports the attributes namely colspan and
rowspan which helps to merge the table cells accordingly.
The colspan attribute accepts a numeric value and merges specified numeric value
of columns together.
Colspan Syntax:

The row span attribute accepts a numeric value and merges specified
numeric value of rows together.
Rowspan Syntax:

HTML Table Borders:


HTML tables can have borders of different styles and shapes.
• Collapsed Table Borders
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
• Style Table Borders
th, td {
background-color: #96D4D4;
}
• Round Table Borders
table, th, td {
border: 1px solid black;
border-radius: 10px;
}
• Dotted Table Borders
th, td {
border-style: dotted;
}

HTML tables can


have borders of different styles and shapes.
HTML Table Padding & Spacing:

HTML tables can adjust the padding inside the cells, and also
the space between the cells.

HTML Table - Cell Padding


Cell padding is the space between the cell edges and the cell content.
By default the padding is set to 0.
To add padding on table cells, use the CSS padding property:

Example
th , td {
padding: 15px;
}

HTML Forms:
An HTML form is used to collect user input. The user input is most often
sent to a server for processing.
The form can be created using <form>...</form> tag of HTML.
• method: Defaults to HTTP "get" method of submission to the
server. To use HTTP "post", use method="post"
• action: The URL to which the form data has to be submitted
• target: Specifies if the submitted result will open in the current
window, a new tab, or on a new frame

The form input element is used to collect details from the user.
Input type - text:
A single-line text field. The value attribute defines the value of the input
field. Name: <input type="text" value="">

Input type - password:


An input field can be used to enter a password.
Email-Id: <input type="email">

Input type - email:


• An input field that accepts email addresses.
Email-Id: <input type="email">
Input type - number:
• Defines an input text box, where the user can enter only numerical input.
Age: <input type="number">

Color and Date Pickers:


We have various picker-elements in HTML forms such as color-picker and
date-picker elements.
Input type - color:
Defines a color picker.
Ex:
Choose a color: <input type="color">

Input type – datetime-local:


 Choose a date and time: <input type="datetime-local"/>

Input type – week:


 Select a week: <input type="week"/>
Similarly, we have date pickers for month and week as well.

Select and Datalist Elements


We have <select> and <datalist> elements in HTML which helps to
collect input data from user a

<select> element :
• Defines a drop-down list.
Ex:
Country code: <select >
<option value="">-- Please choose a country code --</option>
<option value="+213">+213</option>
<option value="+91">+91</option>
<option value="+244">+244</option>
<option value="+61">+61</option>
<option value="+973">+973</option>
</select>
<datalist> element:
• Defines a set of pre-defined options available to choose for an
<input> element.

Ex:
Country: <input list="countries">
<datalist id="countries">
<option value="India">
<option value="France">
<option value="Singapore">
<option value="Thailand">
<option value="United Arab Emirates">
<option value="United States of America">
</datalist>

Input Elements – Attributes


The following are some of the attributes which can be used with HTML
input elements
Placeholder:
The placeholder attribute specifies a value that appears in the textbox as
below.

Pattern:
The pattern attribute creates a custom pattern validator.
Multiple:
The multiple attribute value allows the user to enter/select/upload more
than one value.

Min, Max, and Step:


The following are some of the attributes which are used only with range
and number input types
•min: Specifies a minimum acceptable value.
•max: Specifies maximum acceptable value.

Required:
The required attribute specifies that user input is a must.

.
Media
The media attribute specifies what media/device the linked
document is optimized for.
This attribute is used to specify that the target URL is designed for
special devices (like iPhone) , speech or print med

Image Element:Embedding images to a web page can be done with the


<img>...</img> tag. The <img> tag has attributes 'src' and 'alt' where src
defines the location of the image and alt defines the alternative text if it is
failed to load the image inside the web page.

Audio Element:
Embedding audio to a web page can be done with <audio>...</audio>
tag. The <audio> tag has an attribute 'src' which defines the
location of the audio file. It also has an attribute 'controls' which
specifies whether to display the player controls.

<audio src="audio.mp3" controls="controls"></audio>


Video Element:
Videos can be embedded into web pages using <video>…</video>
tag. The <audio> tag has an attribute 'src' which defines the
location of the audio file.
<video src ="myVideo.mp4" controls="controls"></video>

iframe:
We might have requirements to include documents, videos, interactive
videos, or even other web content into a web page directly from
external sources
.It is defined using <iframe>…</iframe> tag.
EXPERIMENT-3
COURSE NAME: JAVASCRIPT
A. TYPES OF IDENTIFIERS:
JavaScript identifiers are the name that we give to variables, objects,
functions, arrays, classes, etc. We must use a unique name so as to identify them.
We then use the identifier to refer to the variable, functions, etc elsewhere in the
program. There are certain rules & restrictions that we must follow when we name
an identifier.
Here are the main types of identifiers in JavaScript:
1. Variables:
 Used to store data values.
 Example: ‘let myVariable=10’;
2. Constants:
 Similar to variables, bute their values cannot be reassigned.
 Example: ’const PI=3.14’;
3. Functions:
 Used to define reusable blocks of code.
 Example: ’function myFunction() {/*code*/}’
4. Classes:
 Used to create objects with shared properties and methods.
 Example: ‘class Dog{/*code*/}’
5. Interfaces:
 Used in the context of object-oriented programming to define the
structure that classes must adhere to.
 Example: ‘interface Shape {/*code*/}’

B. PRIMITIVE AND NON-PRIMITIVE DATATYPES:


Every Variable has a data types that tells what kind of data is being stored
in a variable. There are two types of data types in JavaScript.
 Primitive data types
 Non-primitive data types
Primitive data types:
The predefined data types provided by JavaScript language are known as
primitive data types. Primitive data types are also known as in-built data types.
Below is a list of Primitive Data Types with proper descriptions and examples:
Number:
Number data type in JavaScript can be used to hold decimal values as
well as values without decimals.
String
The string data type in JavaScript represents a sequence of characters
thet are surrounded by single or double quites.
Undefined
The meaning of undefined is ‘value is not assigned’.
Boolean
The Boolean data type can accept only two values i.e. true and
false.
Null
This data type can hold only one possible value that is null.
Symbol
This data type is used to create objects which will always be unique.
These objects can be created using Symbol constructor.
Non-primitive data types:
The data types that are derived from primitive data types of the
JavaScript language are known as non-primitive data types. It is also known as
derived data types or reference data types.
Below is a list of Non-primitive data types.
Object
An object in JavaScript is an entity having properties and methods.
Everything is an object in JavaScript.
How to create an object in JavaScript:
Array
With the help of an array, we can store more than one element under a single name.
C. OPERATORS AND TYPES OF OPERATORS:
JavaScript operators operate the operands, these are
symbols that are used to manipulate a certain value or operand. Operators are used
to performing specific mathematical and logical on operands.
In JavaScript, operators are used to compare values, perform arithmetic
operations, etc.

There are different types of JavaScript operators:

 Arithmetic Operators
 Assignment Operators
 Comparison Operators
 Logical Operators
 Bitwise Operators
 Type Operators

JavaScript Arithmetic Operators

Arithmetic Operators are used to perform arithmetic on numbers:

JavaScript Assignment Operators

Assignment Operators assign values to JavaScript variables.

The Addition Assignment operator (+=) adda a value to a variable.


JavaScript Comparison Operators

Comparison operators are mainly used to perform the logical


operations that determine the equality or difference between the values.

JavaScript Logical Operators

These operators are used to determine the logic between variables or


values.
JavaScript Type Operators

JavaScript Bitwise Operators

Bit operators work on 32 bits numbers.

Any numeric operand in the operation is converted into a 32 bit it number. The
result is converted back to a JavaScript number.

D. TYPES OF STATEMENTS:
There are two types of statements in JavaScript. They are:
1. Non-conditional Statements.
2. Conditional Statements.
1. Non-Conditional Statements:
Non-conditional statements in JavaScript are statements that do not
involve conditional logic, such as if, else, switch, etc. These statements
are executed regardless of any condition being met. Some common
non-conditional statements in JavaScript include:
o Declaration Statements:
-Variable declaration (‘var’, ’let’, ’const’
-Function declaration(‘function’)
o Loop Statements:
- ‘for’ loop
- ‘while’ loop
- ‘do…while’ loop
- ‘for…in’ loop
- ‘for…of’ loop
o Control Flow Statements:
- ‘break’
- ‘continue’
- ‘return

2.Conditional Statements:
Conditional Statements in JavaScript allow you to execute specific
blocks of code based on conditions. If the condition meets then a particular block of
action will be executed otherwise it will execute another block of action that
satisfies that particular condition.
There are several methods that can be used to perform Conditional Statements in
JavaScript.
o If Statement
o If-else Statement
o Else if statement
o Switch Statement
o Ternary Statement
JavaScript if Statement
The if statement is used to evaluate a particular condition. If the condition
holds true, the associated code block is executed.
Syntax:
JavaScript if-else Statement
The if-else statement will perform some action for a specific condition. Here
we are using the else statement in which the else statement is written after the if
statement and it has no condition in their code block.
Syntax:

JavaScript else if Statement


The else if statement in JavaScript allows handling multiple possible
conditions and outputs, evaluating more than two options based on whether the
conditions are true or false.
Syntax:

E. TYPES OF LOOPS:
JavaScript Loops are powerful tools for performing repetitive tasks
efficiently. Loops in JavaScript execute a block of code again and again while the
condition is true.
There are different types of loops in JavaScript:
 for Loop
 while Loop
 do-while Loop
 Break Statement
 Continue Statement
 Infinite Loop (Loop Error)

JavaScript for Loop


The JS for loop provides a concise way of writing the loop structure. The
for loop contains initialization, condition, and increment/decrement in one line
thereby providing a shorter, easy-to-debug structure of looping.
Syntax:

JavaScript while Loop


The JS while loop is a control flow statement that allows code to be
executed repeatedly based on a given Boolean condition. The while loop can be
thought of as a repeating if statement.
Syntax:

JavaScript do-while Loop


The JS do-while loop is similar to the while loop with the only difference is
that it checks for the condition after executing the statements, and therefore is an
example of an Exit Control Loop. It executes loop content at least once event the
condition is false.
Syntax:
JavaScript Break Statement
JS break statement is used to terminate the execution of the loop or switch
statement when the condition is true.
Syntax:

JavaScript Continue Statement


JS continue statement is used to break the iteration of the loop and follow
with the next iteration. The break in iteration is possible only when the specified
condition going to occur. The major difference between the continue and break
statement is that the break statement breaks out of the loop completely while
continue is used to break one statement and iterate to the next statement.
Syntax:
EXPERIMENT – 4
Java Script
MODULE 1: Types of Functions, Declaring and Invoking Function, Arrow
Function, Function Parameters, Nested Function, Built-in Functions, Variable
Scope in Functions.
TYPES OF FUNCTIONS
• JavaScript has two types of functions.
1. User-defined functions.
2. Built-in functions.

FUNCTION INVOCATION AND DECLARATION


• To use a function, it must be defined or declared and then it can be invoked anywhere in the
program.
• A function declaration also called a function definition, consists of the function keyword, followed
by:
 Function name
 A list of parameters to the function separated by commas and enclosed in parentheses, if any.
 A set of JavaScript statements that define the function, also called a function body, enclosed in
curly brackets {…}

SYNTAX
Function declaration Example

FUNCTION INVOCATION
The code written inside the function body will be executed only when it is invoked or called.

SYNTAX FOR FUNCTION INVOCATION

Example
ANONYMOUS
FUNCTION
• In JavaScript, functions are first-class objects. This means, that you can assign a function as a
value to a variable. For example.

• Here, a function without a name is called an anonymous function which is assigned to a variable
say Hello.

ARROW FUNCTION
• JavaScript has introduced a new and concise way of writing functions using arrow notation. The
arrow function is one of the easiest ways to declare an anonymous function .

• There are two parts for the Arrow function syntax:


1. let say Hello = ()  This declares a variable say Hello and assigns a function to it using () to
just say that the variable is a function.
2. => { }  This declares the body of the function with an arrow and the curly braces.

DIFFERENT SECENARIOS OF ARROW FUNCTIONS


• SYNTAX_1: (multi parameter, multi-line code:)
• If code is in multiple lines, use{}

• SYNTAX-2:(No parameter, single line code:)


• If the code is single line,{} is not required. The expression is evaluated automatically returned

THIS KEYWORD IN ARROW FUNCTION


• Arrow function also adds a great difference with respect to the context object – 'this' reference.
• Consider the below code where a regular function is defined within a method
this in Arrow Functions:
• Arrow functions, on the other hand, don't have their own this context. Instead, they inherit
the this value from the enclosing lexical scope (i.e., the context in which they are defined).

• This means that the value of this inside an arrow function is determined by where the
arrow function is written, not where it is called.

• For normal function the value of this depends upon which object is calling the function

• But for arrow function it does not depend on which is calling the function.
• For arrow function it depends on its outer context(global context)
• The global context in JavaScript refers to the outermost scope or environment where
JavaScript code is executed. It represents the highest level of scope in a JavaScript
program and includes variables, functions, and objects that are accessible throughout the
entire program.

FUNCTION PARAMETERS
• Function parameters are the variables that are defined in the function definition and the values
passed to the function when it is invoked are called arguments.
• In JavaScript, function definition does not have any data type specified for the parameters, and
type checking is not performed on the arguments passed to the function.
• JavaScript does not throw any error if the number of arguments passed during a function
invocation doesn’t match with the number of parameters listed during the function definition. If
the number of parameters is more than the number of arguments, then the parameters that have no
corresponding arguments are set to undefined

DEFAULT PARAMETERS
 JavaScript introduces an option to assign default values in functions
 In the above example, when the function is invoked with two parameters, the default value of
num2 will be overridden and considered when the value is omitted while calling.

REST PARAMETERS
• Rest parameter syntax allows to hold an indefinite number of arguments in the form of an
array
• The rest of the parameters can be included in the function definition by using three dots
( … ) followed by the name of the array that will hold them.
• The rest parameter should always be the last parameter in the function definition

Syntax

Example

In the above example, the first two array elements ‘Andrew’ and 'James’ have been destructured into
individual function parameters arg1 and arg2

NESTED FUNCTIONS
• In JavaScript, it is perfectly normal to have functions inside functions. The function within another
function body is called a nested function.
• The nested function is private to the container function and cannot be invoked from outside the
container function.
BUILT IN FUNCTIONS
• JavaScript comes with certain built-in functions. To use them, they need to be invoked.

VARIABLE SCOPE
• Variable declaration in the JavaScript program can be done within the function or outside the
function. But the accessibility of the variable to other parts of the same program is decided based
on the place of its declaration. This accessibility of a variable is referred to as scope.
• JavaScript scopes can be of three types:
• Global scope
• Local scope
• Block scope

GLOBAL SCOPE
• Variables defined outside function have Global Scope and they are accessible anywhere in the
program.

LOCAL SCOPE
• Variables declared inside the function would have local scope. These variables cannot be accessed
outside the declared function block

Block Scope
• In 2015, JavaScript introduced two new keywords to declare variables: let and const.
• Variables declared with 'var' keyword are function-scoped whereas variables declared with 'let' and
'const' are block-scoped and they exist only in the block in which they are defined

• In the above example, the variable flag declared inside 'if' block is accessible outside the block
since it has function scope
• Modifying the code to use 'let' variable will result in an error:

• The usage of 'let' in the above code snippet has restricted the variable scope only to 'if' block.
• 'const' has the same scope as that of 'let' i.e., block scope.

MODULE 2: Working With Classes, Creating and Inheriting Classes


WORKING WITH CLASSES
• In 2015, JavaScript introduced the concept of the Class.
• Classes and Objects in JavaScript coding can be created similar to any other Object-
Oriented language.
• Classes can also have methods performing different logic using the class properties respectively.
• The new feature like Class and Inheritance eases the development and work with Classes in the
application.
• JavaScript is an object-based language based on prototypes and allows to create hierarchies of
objects and to have inheritance of properties and their values.
• The Class syntax is built on top of the existing prototype-based inheritance model.

INHERITANCE CLASSES
• In JavaScript, one class can inherit another class using the extends keyword. The subclass inherits
all the methods ( both static and non-static ) of the parent class.
• Inheritance enables the reusability and extensibility of a given class.
• JavaScript uses prototypal inheritance which is quite complex and unreadable. But, now you
have 'extends' keyword which makes it easy to inherit the existing classes.
• Keyword super can be used to refer to base class methods/constructors from a subclass

MODULE 3: In-built Events and Handlers


EVENTS IN JS
 When execution of JavaScript code is delayed or deferred till some event occurs, the execution is
called deferred mode execution. This makes JavaScript an action-oriented language.
 Let us understand how JavaScript executes as a reaction to these events.

IN-BUILT EVENT HANDLERS

WIRING THE EVENTS


• Event handlers are associated with HTML elements and are responsible to handle or listen to the
event taking place on the respective element

Syntax:

EXCEPTION HANDLING
• Exception handling is accomplished with a try...catch statement. When the program encounters an
exception, the program will terminate in an unfriendly manner. To protect against this, the code
can be placed in a try...catch statement and avoid terminating the program unexpectedly.
• Try statements: It lets the developer validate a block of code whether it will result in some errors
or not.
• Catch statements: It lets the developer handle the error without terminating the program in an
unfriendly manner.
• Throw statements: It helps the developer to create custom errors.
• Finally statements: It lets the developer execute code, after the try and catch block
execution, irrespective of the result

MODULE 4: Working with Objects, Types of Objects, Creating Objects,


Combining and cloning Objects using Spread operator, Destructuring Objects,
Browser Object Model, Document Object Model
WORKING WITH OBJECTS
• In any programming language when real-world entities are to be coded, then variables are used.
For most of the scenarios, a variable to hold data that represents the collection of properties is
required.
• For instance, to create an online portal for the car industry, Car as an entity must be modelled so
that it can hold a group of properties.
• Such type of variable in JavaScript is called an Object. An object consists of state and behavior.
• The State of an entity represents properties that can be modeled as key-value pairs.
• The Behavior of an entity represents the observable effect of an operation performed on it and is
modeled using functions

TYPES OF OBJECTS

CREATING OBJECTS
• In JavaScript objects, the state and behaviour is represented as a collection of properties
• Each property is a [key-value] pair where the key is a string and the value can be any JavaScript
primitive type value, an object, or even a function.
• JavaScript objects can be created using two different approaches

CREATING OBJECTS USING OBJECT LITERALS


• Objects can be created using object literal notation. Object literal notation is a comma-separated
list of name-value pairs wrapped inside curly braces. This promotes the encapsulation of data in a
tidy package. This is how the objects in JavaScript are created using the literal notation:

Syntax:
CREATING OBJECTS USING FUNCTION CONSTRUCTOR
• Constructor functions are used to create multiple instances of objects with the same structure and
behavior.
• They define a blueprint for creating objects by using a function as a template.
• Constructor functions use the new keyword to create new instances of objects based on the defined
blueprint.
• Here's an example of creating an object using a constructor function:

COMBINING AND CLONING OF OBJECTS USING SPREAD OPERATOR

ACCESSING OBJECT PROPERTIES


• After the object has been created, its variables or methods can be accessed in two different ways:
• Using
• dot operator
• bracket operator

DESTRUCTING OBJECTS
 Destructuring objects in JavaScript allows you to extract multiple properties from an object and
assign them to variables in a concise and readable way. It's a powerful feature introduced in
ECMAScript 6 (ES6) that simplifies working with objects.
 In the below example an object is destructured into individual variables:
OBJECT DESTRUCTURING IN FUNCTIONS
The property 'country' of the object has been destructured and captured as a function parameter.

BUILT IN OBJECTS
• The Global object allows to declare variables and functions that can be accessed anywhere.

• By default, these are built into the language or the environment.

• They are different built-in objects in JavaScript

 Date
 String
 Math
 RegEx
 JSON

Browser Object Model


As you know that, JavaScript is capable of dynamically manipulating the content and style of HTML
elements of the web page currently rendered on the browser. The content given for para during HTML
creation or the style given for heading during HTML creation can be changed even after the page has
arrived on the browser.
Sample HTML Code:

To access an element in the HTML page, following methods can be used on the
'document' object from DOM.
 getElementById(x)
 getElementsByTagName(x)
 getElementsByClassName()
 querySelectorAll()
InnerHeight: This property holds the inner height of the window’s content area.

InnerWidth: This property holds the inner width of the window’s content area
OuterHeight: This property holds the outer height of the window including toolbars and scrollbars.
OuterWidth: This property holds the outer width of the window including toolbars and scrollbars.
LocalStorage: This property allows access to object that stores data without any expiration date
SessionStorage: This property allows access to objects that store data valid only for the current
session.

Methods
 open() method, opens a new window. Usage: window.open ("http://www.xyz.com");
 close() method, closes the current window. Usage: window.close();

If required, BOM also gives a specific object to target only one of the window properties. For
example, if the concern is about the list of URLs that have been visited by the user and there is no
need for any other information about the browser, BOM gives the 'history' object for this. It
provides programmatic navigation to one of the URLs previously visited by the user. Following
are the properties or methods that helps in doing so.
Property:
length returns the number of elements in the History list. Usage: history.length;

Methods:
back() method, loads previous URL from history list. Usage: history.back();
forward() method, loads next URL from history list. Usage: history.forward();
go() method, loads previous URL present at the given number from the history list.
It contains information about the client, that is, the browser on which the web page is
rendered. The following properties and methods help in getting this information.

appName: Returns the name of the client.


appVersion: Returns platform (operating system) and version of the client
(browser).
Platform: Returns the name of the user's operating system
userAgent: Returns string equivalent to HTTP user-agent request header.

Document Object Model

These nodes appear in a hierarchical structure inside the browser. And this
hierarchical relationship between the nodes allows us to traverse through the
DOM tree.
 The top node is called the root. It does not have any parents.
 Every other node in the tree belongs to one parent.
 Every node may have several children.
 Nodes with the same parent are referred to as siblings.
parentNode: Returns a Node object that is the parent node of the specified node. This
property can be retrieved and cannot set it.
childNodes: Returns NodeList object, i.e collection of child nodes of the specified node.
Each child can be accessed by an index number that refers to its position inside the parent
element. The first position is at index '0'.
firstChild: Returns Node object which is the first child of the specified node. Its is
equivalent to childNodes[0].
lastChild: Returns Node object which is the last child of the specified node.
nextSibling: Returns the Node object of the node that immediately follows the specified
node at the same tree level.
previousSibling: Returns the Node object of the node that the previous node of the
specified node at the same tree level.
Experiment – 5
Arrays, Asynchronous Programming, Modules in JavaScript
Arrays in JavaScript:
 In JavaScript, an array is a special type of object used to store multiple values in a single
variable.
 Arrays can hold different types of data, including numbers, strings, objects, and even other
arrays.
 We can access the values of arrays by referring to an index number.
Syntax of array:
const array_name = [item1, item2, ...];

Creating arrays:
You can create an array using square brackets [] and separating each element with a comma.
Creating an empty array:
let myArray = [];
Creating an array with elements:
let fruits = ['apple', 'banana', 'orange'];

Accessing elements of an array:


You can access elements of an array using bracket notation []. Arrays in JavaScript are zero-
indexed, meaning the first element is at index 0.
let fruits = ['apple', 'banana', 'orange'];
console.log(fruits[0]); // Outputs: "apple"
console.log(fruits[1]); // Outputs: "banana"
console.log(fruits[2]); // Outputs: "orange“

Modifying Elements:
You can modify elements in an array by accessing them using their index and assigning a new
value.
fruits[1] = 'kiwi';
console.log(fruits); // Outputs: ["apple", "kiwi", "orange"]

Array Methods:
JavaScript provides a variety of methods to manipulate arrays:
let fruits = ['apple', ‘kiwi', 'orange'];
Push:
push() adds elements to the end of an array.
fruits.push('grape');
console.log(fruits); // Outputs: ["apple", "kiwi", "orange", "grape"]
Pop:
pop() removes the last element of an array.
let lastFruit = fruits.pop();
console.log(lastFruit); // Outputs: "grape"
console.log(fruits); // Outputs: ["apple", "kiwi", "orange"]
Unshift:
Unshift() adds elements to the beginning of an array.
let fruits = ['apple', ‘kiwi', 'orange'];
fruits.unshift('grape');
console.log(fruits); // Outputs: ["grape", "apple", "kiwi", "orange"]
Shift:
Shift() removes the first element.
let firstFruit = fruits.shift();
console.log(firstFruit); // Outputs: "grape"
console.log(fruits); // Outputs: ["apple", "kiwi", "orange"]
Slice:
slice() method extracts a section of an array and returns a new array.
let fruits = ['apple', ‘kiwi', 'orange'];
let citrus = fruits.slice(1, 3);
console.log(citrus); // Outputs: ["kiwi", "orange"]
Concat:
concat() method is used to merge two or more arrays. It does not modify the existing arrays but
instead returns a new array.
let moreFruits = ['grapefruit', 'cherry'];
let allFruits = fruits.concat(moreFruits);
console.log(allFruits); // Outputs: ["apple", "kiwi", "orange", "grapefruit", "cherry"]
Array Destructuring :
Array destructuring in JavaScript allows you to extract values from arrays and assign them
to variables in a concise and convenient way. It's a handy feature introduced in ECMAScript 6
(ES6) that simplifies working with arrays.
Example:
let colors = ['red', 'green', 'blue'];
// Destructuring assignment
let [firstColor, secondColor, thirdColor] = colors;
console.log(firstColor); // Outputs: "red"
console.log(secondColor); // Outputs: "green"
console.log(thirdColor); // Outputs: "blue"
Skipping Elements:
You can skip elements in the array by leaving placeholders (commas) for them.
let colors = ['red', 'green', 'blue'];
let [first, , third] = colors;
console.log(first); // Outputs: "red"
console.log(third); // Outputs: "blue"
Using Rest Syntax:
You can use the rest syntax (...) to capture remaining elements into a new array.
let [head, ...tail] = colors;
console.log(head); // Outputs: "red"
console.log(tail); // Outputs: ["green", "blue"]
Default Values:
You can provide default values for variables in case the array doesn't have enough elements.
let [color1, color2, color3, color4 = 'yellow'] = colors;
console.log(color1); // Outputs: "red"
console.log(color2); // Outputs: "green"
console.log(color3); // Outputs: "blue"
console.log(color4); // Outputs: "yellow"

Asynchronous programming:
Asynchronous programming in JavaScript allows you to execute code non-sequentially,
meaning that certain operations can be started without having to wait for other operations to
complete. This is particularly useful for tasks like making network requests, reading files, or
executing long-running computations without blocking the execution of other code.
JavaScript supports asynchronous programming through various mechanisms:

 Callbacks
 Promises
 async/await syntax.
Callbacks in java Script:
Callbacks in JavaScript are functions passed as arguments to other functions, which are
then invoked or "called back" at a later time, usually after some asynchronous operation has
completed. Callbacks are a fundamental concept in JavaScript, especially when dealing with
asynchronous code. They allow you to control the flow of execution and handle the result of an
asynchronous operation once it's finished.
Fetch data using Callbacks:
function fetchData(callback) {
// Simulating an asynchronous operation
setTimeout(() => {
const data = 'Data fetched successfully';
// Call the callback function with the data
callback(data);
}, 1000);
}
// Define a callback function
function processResult(result) {
console.log(result);
}
// Call the function and pass the callback
fetchData(processResult);

Handling errors using callbacks:


function fetchData(callback, errorCallback) {
setTimeout(() => {
const error = true; // Simulate no error for this example
if (error) {
errorCallback('Error fetching data');
} else {
const data = 'Data fetched successfully';
// Call the callback function with the data
callback(data);
}
}, 1000);
}
// Define a callback function
function processResult(result) {
console.log(result);
}
// Define an error callback function
function handleErrors(error) {
console.error('Error:', error);
}
fetchData(processResult, handleErrors);

Promises:
Promise is a way to handle Asynchronous operations. A promise is an object that
represents a result of operation that will be returned at some point in the future.
Promise States:
A promise will be in any one of the three states:
 Pending: Neither fulfilled nor rejected
 Fulfilled: Operation completed successfully
 Rejected: Operation failed.

Fetch data using promises :


import fetch from 'node-fetch';
const url="https://official-joke-api.appspot.com/random_joke";
const responsePromise=fetch(url);
responsePromise.then((response)=>{
return response.json();
}).then((jsonData) => {
console.log(jsonData);
})
Handling errors using promises :
import fetch from 'node-fetch';
const url="https://official-joke-api.appspot.com/random_joke";
const responsePromise=fetch(url);
responsePromise.then((response)=>{
return response.json();
}).then((jsonData) => {
console.log(jsonData);
}).catch((error)=>{
console.log(`Error is ${error}`);
})

Async and Await:


Async and await is a modern JavaScript feature that allows you to write asynchronous
code in a synchronous-like manner, making it easier to read and reason about asynchronous
operations. Async/await is built on top of promises and provides a way to handle asynchronous
code flows using synchronous style syntax.
Fetching and error handling using Async and Await :
import fetch from 'node-fetch';
const url="https://official-joke-api.appspot.com/random_joke";
const data=async()=>{
try{
const response=await fetch(url);
const jsonData=await response.json();
console.log(jsonData);
}
catch(err){
console.log(`Error is ${err}`);
}
}
data();

JavaScript Modules:
JavaScript, like most programming languages, was initially used for small tasks. But as its
popularity grew, so did the amount of code that needed to be written. Having a large amount of
code in a single file can be problematic, so it's helpful to split the code into multiple parts. This is
where modules come in handy.
JavaScript modules are a way to organize and structure code. They allow developers to
break their code into smaller, reusable pieces. You can think about them as smaller pieces of code
that you can import and export between different parts of an application.
Benefits of using Modules:
 More Organized Code
 Code Reusability
 No Naming Conflicts
To use modules, we need to import them in our code. The code must be exported to import it
in other files.
Types of File Exports in JavaScript:
• Default export
• Named export
Default export:
Example:
const sum = (a, b) =>{
return a + b;
}
Export default sum;
Named export:
const sum = (a, b) =>{
return a + b;
}
const sub = (a, b) =>{
return a - b;
}
export {sum, sub};
Importing Modules:
 import a single default export
 import sum from “calc.js”
 import a single named export
 import {sum} from “calc.js”
 import multiple named exports
 import {sum, sub} from “calc.js”
 import an entire module
 import * as calc from “calc.js”
calc.sum(2,3);
calc.sub(10,5);
Using import aliases in Javascript:
Import aliases are where you take your standard import, but instead of using a pre-defined name
by the exporting module, you use a name that is defined in the importing module.
Syntax:
For named exports:
export {Something1, Something2}
import {Something1 as MySomething} from "my-module.js"
For default exports:
export default Something
import MySomething from "my-module.js"
EXPERIMENT – 6
Node.js
a) Module Name: How to use Node.js.
Verify how to execute different functions successfully in the Node.js platform.
b) Module Name: Create a web server in Node.js
Write a program to show the workflow of JavaScript code executable by creating web server in
Node.js.
c) Module Name: Modular programming in Node.js
Write a Node.js module to show the workflow of Modularization of Node application.
d) Module Name: Restarting Node Application
Write a program to show the workflow of restarting a Node application.
e) Module Name: File Operations
Create a text file src.txt and add the following data to it. Mongo, Express, Angular, Node.

a) Module Name: How to use Node.js.


Verify how to execute different functions successfully in the Node.js platform.

How to install & Use Node.js

 Install Node.js: First, you need to download and install Node.js from the official website
(https://nodejs.org).
 Write Your JavaScript Code: Create a JavaScript file (e.g., app.js) where you'll write your
Node.js code.
 Write Your Node.js Code: In your JavaScript file (app.js), you can write server-side code
using Node.js APIs.
 Run Your Node.js Application: You can run your Node.js application by navigating to its
directory in the terminal and running node app.js.

Functions

In Node.js, functions work similarly to functions in JavaScript in the browser, with some
additional capabilities and considerations for server-side programming.

 To use a function, it must be defined or declared and then it can be invoked anywhere in
the program.
 A function declaration also called a function definition, consists of the function keyword,
followed by: function name
 A list of parameters to the function separated by commas and enclosed in parentheses, if
any.
 A set of statements that define the function, also called a function body, enclosed in curly
brackets { }

Syntax:
Function Declaration:

Example:

Function Invoking:

The code written inside the function body will be executed only when it is invoked or called.

Syntax:

Example:

Different types of functions:

1. Anonymous Functions: An anonymous function is a function without a name. In


JavaScript, anonymous functions are often used as arguments to other functions, as part of
an expression, or to create closures.
Here's an example of an anonymous function:

Here, a function without a name is called an anonymous function which is assigned to a


variable result.
2. Arrow Functions: Arrow functions are a concise way to write functions in JavaScript,
including in Node.js. They provide a more compact syntax compared to traditional
function expressions and lexically bind this value, which can be especially useful in
callback functions or when dealing with nested functions.
Arrow functions are defined using a syntax that omits the function keyword and uses an
arrow => to separate the parameters from the function body.

3. Asynchronous Functions: Node.js is particularly known for its support for asynchronous
programming. Functions can be defined to execute asynchronously using callbacks,
Promises, or the async /await syntax.

b) Module Name: Create a web server in Node.js


Write a program to show the workflow of JavaScript code executable by
creating web server in Node.js.

Creating a Web Server

The example of a web server written in Node.js using the built-in http module:
Steps to save and run the code

 Save this code in a file, for example server.js. Then, you can run this script using Node.js
by executing node server in your terminal or command prompt. This will start a web
server listening on http://127.0.0.1:3000/
 You can visit http://127.0.0.1:3000/ in your web browser, and you should see the message
"Hello, World!" displayed in the browser window.

Functions used in creating the web server

 Import the http module.


 Define the hostname and port number.
 createServer( ) method is used to create the server and the server is used as an object.
 setHeader( ) is used to set the response header with Content-Type of text/plain.
 end( ) is used to send a response to the client.
 listen( ) is used to start the server and have it listen for connections on the specified
hostname and port.

c) Module Name: Modular programming in Node.js


Write a Node.js module to show the workflow of Modularization of Node
application.

Modular Programming

Modular programming in Node.js involves breaking down your code into separate modules or
files, each responsible for a specific functionality or feature . This approach promotes code
organization, reusability, and maintainability.

There are several ways to implement modular programming in Node.js:


 CommonJS Modules: Node.js uses the CommonJS module system by default. You
can create modules by defining functions, objects, or variables within a file and then
export them using module.exports. Other files can import these modules using require.
 ES Modules (ECMA Script Modules): Starting from Node.js version 12, you can
also use ES modules. ES modules use import and export syntax. To use ES modules,
you need to specify "type": "module" in your package.json file.
 Creating Custom Modules: You can create your own modules encapsulating
functionality and then reuse them across your application or even publish them as npm
packages.
 Using Third-Party Modules: Node.js has a rich ecosystem of third-party modules
available through npm. You can leverage these modules to add functionality to your
application without reinventing the wheel.
 Modular Routing: In web applications, you can modularize routing using frameworks
like Express.js. You can define routes in separate files and then import them into your
main application file.

Example using Common JS Modules


Here's an example demonstrating modular programming in Node.js: Let's say we have a simple
application that calculates the area of different shapes: a rectangle and a circle. We can organize
our code into separate modules for each shape.

rectangle.js:

Circle.js: (Sub Module)

App.js: (Main File)

Output:
16
50.24

Explanation of Code:

 In the above example : rectangle.js and circle.js contain functions to calculate the area of a
rectangle and a circle, respectively. They export these functions using module.exports.
 app.js is the main file that imports the modules rectangle and circle. It then uses the
functions exported by these modules to calculate and print the areas of a rectangle and a
circle.
 To run this program, ensure all files are in the same directory, and then execute node
app.js in the terminal. This will output the calculated areas of the rectangle and the circle.
 This modular approach makes it easier to manage code as the application grows. Each
module can focus on a specific task, making the codebase more organized and easier to
maintain.

d) Module Name: Restarting Node Application


Write a program to show the workflow of restarting a Node application.
Restarting Node Application

• During development, developers frequently make changes to the codebase.


• Traditional manual server restarts are required to apply these changes.
• Without an automated restart mechanism, this process can be time-consuming and disrupt
the development flow.
• You can use a package like nodemon or pm2, a utility that monitors changes in the source
code of Node.js applications.
• It automatically restarts the server upon detecting code modifications.

Steps to Restart Node Application

• First, install nodemon globally


• Write the below command in Command Prompt to install Nodemon or PM2 Utility.

• Create a simple node.js application, call it app.js

• Create a package.json file with a script to start your application using nodemon.

• Save the changes and run the node application by entering this command in command
prompt.
• Now, whenever you make changes to your app.js file and save it, nodemon will
automatically restart the Node.js application.
• Now the node application runs and the terminal shows following output.

• Then the output is displayed in web browser using server http://localhost:3000/

• Make changes to code in app.js. The application will restart automatically and the
following will be output in terminal.

• Then the changes will be made and reload the server in the browser. And changes will be
displayed.

e) Module Name: File Operations


Create a text file src.txt and add the following data to it. Mongo, Express,
Angular, Node.

File Operations

• In Node.js, file operations are crucial for interacting with the file system, allowing
developers to read, write, and manipulate files.
• The built-in fs module is the primary module used for file operations.
• These built-in modules are used to perform various operations like reading file, writing to
file, existence of file, renaming the file, appending data to file, deleting file, etc.

Writing to File

The fs.writeFile() function is used to asynchronously write data to a file. If the file already exists,
it will be truncated.
Syntax:

Example:

Output:
File has been written.

Reading a File

The fs.readFile() function is used to asynchronously read the contents of a file.

Syntax:

Example:

Output:
File content: Mongo, Express, Angular, Node.

Appending a File

The fs.appendFile() function is used to asynchronously append data to a file.

Syntax:
Example:

Output:
Content has been appended.

Rename a File

The fs.rename() function is used to asynchronously rename a file.

Syntax:

Example:

Output:
File has been renamed.

Delete a File

The fs.unlink() function is used to asynchronously delete a file.

Syntax:
Example:

Output:
File deleted successfully.

Existence of a File

The fs.access() function is used to check if a file or directory exists.

Syntax:

Example:

Output:
File does not exist.
EXPERIMENT - 7
Expess.js
Introduction to Express: Express is a layer built on the top of the Node.js that helps manage server
and routes.

-Node.js does not support request handling, HTTP methods so, this is where Express.js comes into
picture.

-There are 34,372 companies using Express.js.

-It is a back-end framework.

-It also provides a robust set of features to develop applications(web and mobile).

-It is easy to learn, fast, free, flexible and unopinionated ( There isn’t a best way to do something, what
you do is the best way)

-It is all javascript.

-It goes well with node.js.

-Express links quickly with databases like MySQL, MongoDB etc.

-Express makes debugging easier as it identifies the exact part where bugs are.

Advantages of ExpressJS:

1. Express is very easy we can customize and use it as per our needs.

2. A single language JavaScript is used for both front-end and back-end development.

3. It is very fast to link with databases like MySOL, MongoDB.

Dis-Advantages of ExpressJS:

1. No structural way to organizing things.

2. The error messages are not very helpful.

Installing Express (In windows):

Step 1- Download Node.js

Step 2- Now, open your visual studio code, open a new terminal and install npm (node package
manager)

Step 3- After installing npm, you must check the version of npm(Command: npm -v)

Step 4- Create folder(that stores your express file) and open it in visual stdio

Step 5- Now, inside that folder create a file app.js

Step 6- write command: npm init (in terminal).


Press enter

Enter required details...

Package name: ExpressJS group7

Version: 1.0.0

Description: SOC lab

Entry point: app.js

Click enter..

Step 7- Now you will finally install express js for that write command: npm install express

With this Express js will have gotten installed on your system.

Step 8- Now write your first basic program(in app.js).

//First import express

const express= require('express')

//Initialize app using express. .

//with which we can perform tasks(app)

const app=express();

//Creating a route for the method get in the path "/"

app.get('/',(req,res)=>{

res.send("Welcome to JNTN");

})

//The response to our req is shown in the port:4000

app.listen(4000,()=>{

console.log("listening to port 4000");

})

Step 9- Open the terminal, go to the main folder write ‘cd <<folder name>>’, press enter,
and then write the command to run the code: node app.js.

Step 10- Now open chrome and go to local host: 4000 to see the result.
Route:

Each route corresponds to an HTTP method (e.g., GET, POST, PUT,


DELETE) and a specific URL pattern/path.

Example: We define routes using methods like “app.get()” and “app.post()”.

Routers():

Defining routes like above is very tedious to maintain. To separate the routes from our
main index.js file, we will use Express.Route

Route methods:(Examples)
// GET method route
app.get('/', (req, res) => {
res.send('GET request to the homepage')
})

// POST method route


app.post('/', (req, res) => {
res.send('POST request to the homepage')
})

Route paths:(Examples)
//Route path is “/random.text”
app.get('/random.text', (req, res) => {
res.send('random.text')
})

//Route path is “/about”


app.get('/about', (req, res) => {
res.send('about')
})
Route parameters:
***Route parameters are named URL segments that are used to
capture the values specified at their position in the URL***.
EXAMPLE:
Request URL: http://localhost:3000/user/42
req.params: {"userId": "42"}

1. Implementing routing for AdventureTrails application by embedding necessary code


in the routes/ route.js file.

An adventure trails application is a web application, built with Express.js could be a platform
for users to discover, explore, and share information about outdoor trails for activities such as
hiking, biking, or running.

Index.js file:

const express = require('express');

const app = express();

//naming the path as route1

const route1 = require('./routes/route');

// opening file route for path /trail

app.use('/trail', route1);

// Start the server

app.listen(4000,()=>{

console.log("listening to port 4000")

})

routes/route.js file:

const express = require('express');

const router = express.Router();

// Sample trails data (replace this with your actual data source)
const trails = [

{ id: 1, name: 'tirupathi', location: 'India' },

{ id: 2, name: 'srisailam', location: 'India' },

{ id: 3, name: 'Annavaram', location: 'India' }

];

// Route for homepage or list of trails

router.get('/', (req, res) => {

res.send('Welcome to AdventureTrails!');

// Example: res.render('index');

});

// Route for getting all trails

router.get('/trails', (req, res) => {

res.send(trails);

});

// Route for getting a specific trail by ID

router.get('/trails/:id', (req, res) => {

const trailId = parseInt(req.params.id);

const trail = trails.find(trail => trail.id === trailId);

if (trail) {

res.json(trail);

});

// Other routes for creating, updating, and deleting trails can be added here

module.exports = router;
Output:

Middleware
What's middleware?

They are functions.

These middleware functions have access to response obj (res), request object(req) and next in the
application req-res cycle.

It is used for--

1.Security check of user's access/authorization.

2.Body parsing of the request (wheather it have correct requested data).

3.What region data is from.

4.What was the data that was requested.

***Order of writing these middleware functions is important***

Code example for Middleware:


router. use (‘/', function (req, res, next) {

console.log(" req call for middle ware ");

next();

//next method is used to chain the middleware in application.

});

Types of Middleware --

1. Application level middleware – For any route this middleware function works.

Ex: router. use (‘/', function (req, res, next) {

console.log(" req call for middle ware ");

next();

//next method is used to chain the middleware in application.

});

2. Router level middleware – when a route is activated then only these middlewares will work.
Here we can use multiple middlewares.

Ex: app.get (‘/user', function (req, res, next) {

console.log("first req call for middle ware ");

next();

//next method is used to chain the middleware in application.

},

function(req, res, next){

console.log(“Second”);

next();

});

3. Builtin middleware - There will be some builtin middlewares. Ex: express.json


4. Third party middleware – Which adds functionality to Express JS as it cannot parse
data, for which we use a third party middleware i.e, BodyParser.

5. Error handling middleware - To handle errors in requests

2.(i) we want to handle POST submissions.

The POST request is handled in Express using the Post express method. This is used when
there is a requirement of fetching data from the client such as form data. The data sent
through the POST request is stored in the request object

Express requires an additional middleware module to extract incoming data of a POST request.
This middleware is called the “body-parser”. We need to install it and configure it with Express
instance.
You can install body-parser using the following command: npm install body-parser
You need to import this package into your project and tell Express to use this as
middleware. (use postman extension to give input data and view the result—by installing
postman extension in visual stdio)
Source code:

const express = require('express')

const bodyParser = require('body-parser')

const app = express()

app.use(bodyParser.json())

app.use(bodyParser.urlencoded({ extended: false }))//middleware

app.get('/', (req, res) => {

res.send('Hello World!')

})

app.post('/', (req, res) => {

let name = req.body;

res.send('Data Received: ' + JSON.stringify(name));

})

app.listen(3000, () => {

console.log('Example app listening on port 3000!')

})
Choose the HTTP method as "POST" from the dropdown menu.Enter the URL of your Express.js
server. For example, if your server is running locally on port 3000, the URL would be
http://localhost:3000/submit.

Optionally, you can add headers, query parameters, or authentication if your server requires them
Add request body: Switch to the "Body" tab in Postman.
 Select the "raw" option.
 Choose JSON format from the dropdown menu.
 Enter some sample data in JSON format. For example:

"name": "John Doe"

Click on the "Send" button to send the POST request to your Express.js server. Once the request is
sent, you should see the response from your server (localhost: 3000).

Errors in express.js :
In Express.js, errors can occur for various reasons during the execution of your
application. some common types of errors you might encounter are :
“Syntax Errors, Runtime Errors, Database Errors, Custom Errors.”
(II). Custom Errors:
Custom errors are errors that you define yourself to handle specific
scenarios in your application.

1. Create Custom ErrorHandler middleware:

// ErrorHandler.js in middlewares folder.

const ErrorHandler = (err, req, res, next) => {

console.log("Middleware Error Hadnling");

const errStatus = err.statusCode || 500;

const errMsg = err.message || 'Something went wrong';

res.status(errStatus).json({
success: false,
status: errStatus,
message: errMsg,
stack: process.env.NODE_ENV === 'development' ? err.stack : {}
})
}

export default ErrorHandler

2. Attach Custom Error Handler as The Last Middleware to Use

import ErrorHandler from "./middlewares/ErrorHandler.js";

// ERROR HANDLER MIDDLEWARE (Last middleware to use)

app.use(ErrorHandler)

3. How to Call the ErrorHandler

to call the ErrorHandler, Use the next() in Express.


The next function is a function in the Express router which, when invoked, executes the
middleware succeeding the current middleware.
Example:

app.use(“/books”,(req,res,next) => {

try{
// code block to be executed
}catch(err){

next(err);
}

})
Error Response(output):

"success": false,
"status": 500,
"message": "Something went wrong",
"stack": "Error: Custom error message\n at app.get
(/path/to/your/app.js:10:15)\n at Layer.handle [as handle_request]
(/path/to/node_modules/express/lib/router/layer.js:95:5)\n at next
(/path/to/node_modules/express/lib/router/route.js:137:13)\n at
Route.dispatch (/path/to/node_modules/express/lib/router/route.js:112:3)\n
at Layer.handle [as handle_request]
(/path/to/node_modules/express/lib/router/layer.js:95:5)\n at
/path/to/node_modules/express/lib/router/index.js:281:22\n at
Function.process_params
(/path/to/node_modules/express/lib/router/index.js:335:12)\n at next
(/path/to/node_modules/express/lib/router/index.js:275:10)\n at
Function.handle (/path/to/node_modules/express/lib/router/index.js:174:3)\n
at router (/path/to/node_modules/express/lib/router/index.js:47:12)"
}

(III). Logging in express.js:

Logging is the process of recording events, actions, or information from a software


application to a log file or another output destination. In the context of web development
and server-side programming, logging involves capturing and storing various types of
information related to the operation of the application.

Logging is an essential part of software development and maintenance for several reasons:
“Debugging and Troubleshooting, Monitoring and Performance Analysis,
Security Analysis”.

There are various logging libraries available for Node.js and Express.js, such as
“morgan, winston, and bunyan”.

1. Install morgan:

If you haven't already installed morgan, you can do so using npm: npm install morgan

2. Use morgan Middleware:


const express = require('express');
const morgan = require('morgan'); const
app = express(); const port =
3000; // Use morgan
middleware for logging HTTP requests

app.use(morgan('dev'));
// Your routes and other middleware here...
// Start the server
app.listen(port, () => {

console.log(`Server is listening on port ${port}`);

});

If you use the provided logging setup in your Express.js application, the output will be
displayed in the console where your application is running. Here's what the output might
look like:

Server is listening on port 3000

::1 - GET / 200 5.224 ms - 12

::1 - GET /styles.css 404 0.452 ms - 139

::1 - GET /images/logo.png 200 2.392 ms - 2689

::1 - GET /about 200 2.129 ms - 273

::1 - GET /contact 404 1.212 ms – 142

Custom Logging:

If you need more customized logging or want to log additional information, you can create
custom middleware to handle logging.
Code:

app.use((req, res, next) => {

console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);


next();

});

Output for custom logging is:

2022-04-08T12:30:45.678Z - GET /

2022-04-08T12:30:48.123Z - GET /about

2022-04-08T12:30:50.987Z - GET /contact


C)To connect to MongoDB using Mongoose, set up validation
types, and define defaults,
->MongoDB is a popular open-source, NoSQL, document-oriented database.
It's designed to store, retrieve, and manage data in a flexible, scalable, and high-
performance manner. MongoDB uses a flexible document data model that
allows data to be stored in a JSON-like format called BSON (Binary JSON).

->Mongoose is an Object Data Modeling (ODM) library for MongoDB and


Node.js. It provides a straightforward, schema-based solution to model your
application data, and it includes built-in type casting, validation, query building,
and other utilities for interacting with MongoDB.

Here are some key features of Mongoose:

1. **Schema Definition**: Mongoose allows you to define schemas for your


MongoDB documents. Schemas define the structure of your data, including the
types of each field, validation rules, default values, and more.

2. **Model Creation**: Once you've defined a schema, Mongoose allows you


to create a Model based on that schema. Models represent collections in your
MongoDB database and provide an interface for interacting with the documents
in those collections.

3. **Data Validation**: Mongoose provides built-in support for data


validation based on the schema definitions. You can specify validation rules for
each field in your schema, and Mongoose will automatically validate any data
before saving it to the database.

4. **Query Building**: Mongoose provides a powerful query builder that


allows you to construct complex queries for retrieving documents from your
MongoDB collections. You can perform find, findOne, update, delete, and
aggregation operations using Mongoose's query methods.

5. **Middleware**: Mongoose supports middleware functions that allow you


to execute custom logic before or after certain operations, such as saving or
removing documents. Middleware functions can be defined at the schema or
model level.
6. **Population**: Mongoose supports population, which allows you to
reference documents in other collections and automatically retrieve and
populate those referenced documents when querying.

7. **Connection Management**: Mongoose handles connection management


to MongoDB, including connection pooling, reconnection, and error handling. It
provides a simple and consistent way to connect to your MongoDB database
from your Node.js applications.

// Write a Mongoose schema to connect with MongoDB.

To create a Mongoose schema and connect it with MongoDB, you'll need to


follow these steps:

*1st we have to install mongodbcompass and add the database like crud in that
we can create new collection ex:users and add the data

1 open vs code and create a new folder

2. open the terminal in vs code and type npm init –y (//then package.json file
will be created)

3.next install mongoose(npm install express mongoose)

4.create a index.js file


//index.js
const express = require('express')
const mongoose = require('mongoose')
const app=express()
mongoose.connect('mongodb://localhost:27017/crud')
const UserSchema=mongoose.Schema(
{
name:String,
age:Number
}
)
const UserModel = mongoose.model("users",UserSchema)
app.get("/getUsers",(req,res)=>{
UserModel.find({}).then(function(users)
{
res.json(users)
}).catch(function(err){
console.log(err)
})
})

app.listen(3001,() =>{
console.log("server is running")
})

Output:

 Next open the google and type localhost:3001


 Next edit it as localhost:3001/getusers
//Write a program to wrap the Schema into a Model object.

SCHEMA: A schema in Mongoose is a blueprint that defines the structure of


documents within a MongoDB collection. It represents the shape of the data,
including the fields and their types, along with any validation rules, default
values, and other options.

MODEL OBJECT:

In the context of Mongoose and MongoDB, a Model object represents a


collection in your MongoDB database. It provides an interface for querying and
manipulating documents within that collection.

When you define a Mongoose schema and then compile it into a Model using
`mongoose.model()`, you create an instance of the Model object. This Model
object allows you to perform CRUD (Create, Read, Update, Delete) operations
on documents that adhere to the schema.
Here's a breakdown of what a Model object does:

1. **Abstraction of Collection**: The Model object abstracts away the


underlying MongoDB collection. You interact with the Model object to perform
database operations instead of directly accessing the MongoDB collection.

2. **Validation and Type Casting**: When you create documents using the
Model object's methods, Mongoose automatically validates the data against
the schema's defined structure and types. It also performs type casting based
on the schema's definitions.

3. **Querying**: The Model object provides methods for querying the


database to retrieve documents. You can perform find, findOne, or aggregate
queries to retrieve data based on specific criteria.

4. **Manipulating Documents**: You can create, update, and delete


documents using the Model object's methods. These methods ensure that the
operations are performed according to the schema's rules and validation
constraints.

5. **Middleware and Hooks**: Mongoose allows you to define middleware


and hooks at the Model level, which enables you to execute custom logic
before or after certain operations, such as saving or removing documents.

In summary, a Model object in Mongoose encapsulates the behavior and


structure of a MongoDB collection, providing a high-level interface for
interacting with the database while enforcing schema validation and data
consistency.

//program

1.open vs code create a file app.js

2.open terminal give the command npm init –y


3.this will create a package.json file

4.give the command npm install mongodb mongoose

Code in app.js

File: APP.JS

const mongoose = require('mongoose');

mongoose.connect("mongodb://localhost:27017/magesDB");

const mageSchema = new mongoose.Schema({

name: {

type: String,

require: true

},

power_type: {

type: String,

require: true

},

mana_power: Number,

health: Number,

gold: Number

})

const Mage = new mongoose.model("Mage", mageSchema)


const mage_1 = new Mage({

name: "Takashi",

power_type: 'Element',

mana_power: 200,

health: 1000,

gold: 10000

});

mage_1.save();

const mage_2 = new Mage({

name: "Steve",

power_type: 'Physical',

mana_power: "500",

health: "5000",

gold: "50"

})

mage_2.save();

output:

here the model will be saved in the given hierarchy that is mentioned in the
code(magesDB/images)

>node app.js
EXPERIMENT – 8

CRUD Operations in Express.js


CRUD (Create, Read, Update, Delete) operations are fundamental for building
web applications that manage data. Express.js, a popular Node.js framework,
offers a streamlined approach to implementing CRUD functionality using HTTP
methods and data persistence mechanisms.

1. Project Setup:
 Create a new Node.js project directory.
 Initialize it with npm init -y (or yarn init -y).
 Install Express: npm install express (or yarn add express).
2. Data Persistence (Choose One):
 Databases: Select a database like MongoDB, PostgreSQL, MySQL, etc.
based on your project's requirements.
Install the appropriate database driver (e.g., mongoose for MongoDB).
 In-Memory Storage: Consider using express-session or a similar library
for temporary data during the user's session (not recommended for
persistent data).
8.a)Program to perform various CRUD (Create-Read-Update-Delete)
operations using Mongoose library functions.

const express = require('express');


const mongoose = require('mongoose');

// Replace with your MongoDB connection string


const mongoURI = 'mongodb://localhost:27017/your_database_name';

const app = express();


const port = 3000;
// Connect to MongoDB
mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology:
true })
.then(() => console.log('MongoDB connected'))
.catch(err => console.error(err));

// Define the data model (schema)


const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
age: Number
});

const User = mongoose.model('User', userSchema);

// Middleware to parse JSON data in request body


app.use(express.json());

// Create (POST) a new user


app.post('/users', async (req, res) => {
try {
const newUser = new User(req.body);
const savedUser = await newUser.save();
res.status(201).json(savedUser);
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Error creating user' });
}
});

// Read (GET) all users


app.get('/users', async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Error retrieving users' });
}
});

// Read (GET) a user by ID


app.get('/users/:id', async (req, res) => {
try {
const id = req.params.id;
const user = await User.findById(id);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json(user);
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Error retrieving user' });
}
});

// Update (PUT) a user by ID


app.put('/users/:id', async (req, res) => {
try {
const id = req.params.id;
const updatedUser = await User.findByIdAndUpdate(id, req.body, { new:
true }); // 'new: true' returns the updated document
if (!updatedUser) {
return res.status(404).json({ error: 'User not found' });
}
res.json(updatedUser);
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Error updating user' });
}
});

// Delete (DELETE) a user by ID


app.delete('/users/:id', async (req, res) => {
try {
const id = req.params.id;
const deletedUser = await User.findByIdAndDelete(id);
if (!deletedUser) {
return res.status(404).json({ error: 'User not found' });
}
res.json({ message: 'User deleted successfully' });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Error deleting user' });
}
});

app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});

Dependencies: The program requires express and mongoose libraries.


MongoDB Connection: Replace mongoURI with your actual MongoDB
connection string.
User Model: The userSchema defines the structure of a user document with
properties like name, email, and age.
Middleware: express.json() parses incoming JSON data in the request body.

8.b)In the myNotes application, include APIs based on the requirements


provided. (i) API should fetch the details of the notes based on a notesID
which is provided in the URL. Test URL - http://localhost:3000/notes/7555
(ii) API should update the details bas
Express.js is a powerful and versatile framework built on top of Node.js that
simplifies building web applications and APIs. In this module, we'll delve into
using Express.js to create robust and efficient APIs.
Express.js APIs for myNotes Application
I. Fetching Note Details by ID (GET /notes/:id)
1. Route Definition:
const express = require('express');
const app = express();

// ... other middleware and routes

app.get('/notes/:id', async (req, res) => {


const noteId = req.params.id;

try {
// Replace with your logic to retrieve note details from database (e.g., using
Mongoose)
const note = await Note.findById(noteId);

if (!note) {
return res.status(404).json({ message: 'Note not found' });
}

res.json(note);
} catch (error) {
console.error(error);
res.status(500).json({ message: 'Internal server error' });
}
});
 The route handler function async allows for asynchronous database
operations.
 req.params.id extracts the noteId from the URL.
 The placeholder Note.findById(noteId) should be replaced with your
actual database interaction code to fetch the note based on the ID.
 Error handling checks for 404 Not Found if the note doesn't exist and 500
Internal Server Error for unexpected errors.
 The successful response sends the retrieved note data in JSON format.

II. Updating Note Details (PUT /notes/:id)


1. Route Definition:
app.put('/notes/:id', async (req, res) => {
const noteId = req.params.id;
const updatedNote = req.body; // Assumes request body contains updated
note data

try {
// Replace with your logic to update note details in database (e.g., using
Mongoose)
const updatedDocument = await Note.findByIdAndUpdate(noteId,
updatedNote, { new: true });

if (!updatedDocument) {
return res.status(404).json({ message: 'Note not found' });
}

res.json(updatedDocument);
} catch (error) {
console.error(error);
res.status(500).json({ message: 'Internal server error' });
}
});
 This route handles the PUT (update) request.
 req.body is assumed to contain the updated note data in JSON format.
 The placeholder Note.findByIdAndUpdate(noteId, updatedNote, {
new: true }) should be replaced with your actual database interaction
code to update the note. The new: true option ensures the updated
document is returned.
 Error handling is similar to the GET route.
 The successful response sends the updated note data in JSON format.

8.c) Why Session management, Cookies


Session management is a critical aspect of web applications that allows servers
to maintain user state (information) across multiple requests during a session.
Cookies, a simple key-value storage mechanism on the client-side, are a
common technique for session management.
How it Works:
Session Creation: When a user logs in or starts a session, the server generates a
unique identifier (session ID) and stores it on its side (often in a database).
Cookie Creation: The server creates a cookie containing the session ID and
sends it to the user's browser in the HTTP response header.
Subsequent Requests: With the cookie saved locally, the user's browser
automatically sends this cookie back to the server in subsequent requests within
the same session.
Server-Side Processing: The server receives the cookie, retrieves the session
ID, and looks up the associated user session data stored on the server-side. This
allows the server to maintain context and personalize the user's experience.
Session Expiration: Cookies can expire after a predefined time (e.g., when the
browser is closed or after a period of inactivity) or be deleted manually by the
user. Upon expiration or deletion, the server-side session data is also typically
destroyed.

Write a program to explain session management using cookies.


const express = require('express');
const cookieParser = require('cookie-parser'); // Middleware for parsing cookies
const app = express();
const port = 3000;
const secret = 'your_secret_key'; // Replace with a strong secret key for
encryption

app.use(cookieParser(secret)); // Use cookieParser with a secret for signing

app.get('/', (req, res) => {


const userId = req.cookies.userId;

if (userId) {
res.send(`Welcome back, user ${userId}!`);
} else {
// Generate a new session ID and create a cookie
const sessionId = Math.random().toString(36).substring(2, 15);
res.cookie('userId', sessionId, { httpOnly: true, signed: true }); // Secure
flags
res.send('Hello, new user! Your session ID is: ' + sessionId);
}
});

app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});

 We use express and cookie-parser modules.


 A secret key is defined for signing cookies (replace with a strong key).
 The cookieParser middleware is used to parse cookies from incoming
requests.
 The root route (/) checks for a userId cookie.
 If the cookie exists, it welcomes the user by ID.
 If not, it generates a random session ID, sets a signed and httpOnly
cookie, and welcomes the new user with the session ID.
 The server listens on port 3000.

8.d)Sessions
Session Management with Server-Side Sessions
Session management is crucial for web applications to track user state
(information) across multiple requests during a session. In this approach,
session data is stored on the server-side, often in a database or in-memory store,
and a unique identifier (session ID) is used to link that data to the user.
How it Works:
Session Creation: Upon user login or session initiation, the server generates a
unique session ID and stores it on the server-side (e.g., database).
Session ID Delivery: The session ID is typically sent to the client (user's
browser) in a cookie or embedded in the URL (less secure).
Subsequent Requests: With the session ID received, the user's browser
includes it in subsequent requests within the same session.
Server-Side Association: The server receives the session ID and retrieves the
associated session data from its storage mechanism.
Context Maintenance: Based on the retrieved session data, the server can
maintain user context and personalize their experience.
Session Expiration: Sessions can expire after a predefined time (inactivity) or
be explicitly terminated by the user logging out. Upon expiration, the server-
side session data is typically destroyed.
Write a program to explain session management using sessions.
const express = require('express');
const session = require('express-session'); // Middleware for session
management
const app = express();
const port = 3000;
const secret = 'your_secret_key'; // Replace with a strong secret key

app.use(session({
secret: secret,
resave: false, // Don't resave session if no changes
saveUninitialized: true, // Create session even if not modified
cookie: { secure: false } // Set to true for HTTPS only
}));

app.get('/', (req, res) => {


const sessionData = req.session;

if (sessionData.username) {
res.send(`Welcome back, ${sessionData.username}!`);
} else {
// Generate a new session ID and store something in the session
req.session.username = 'Guest';
res.send('Hello, new user!');
}
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
 We use express and express-session modules.
 A secret key is defined for session encryption (replace with a strong key).
 The express-session middleware is used to manage sessions.
 We configure resave: false to avoid unnecessary saves and
saveUninitialized: true to create sessions even without initial data.
 The cookie object configures session cookie behavior (set secure: true for
HTTPS).
 The root route (/) checks if a username property exists in the session data.
 If present, it welcomes the user by name.
 If absent, it creates a new session with a username ('Guest') and welcomes
the new user.
 The server listens on port 3000.
8.e)Why and What Security, Helmet Middleware- Implement security
features in myNotes application
Security in myNotes: Why and What
Importance of Security:

 Protecting User Data: User notes likely contain sensitive information.


Security measures safeguard this data from unauthorized access,
modification, or deletion.
 Preventing Attacks: Web applications are vulnerable to various attacks
like cross-site scripting (XSS), clickjacking, and cross-site request
forgery (CSRF). Security features help mitigate these risks.
 Maintaining Trust: A secure application builds user trust by ensuring
their data is protected and transactions are legitimate.
Helmet Middleware:
Helmet is a popular and powerful Node.js middleware for Express.js
applications that simplifies adding essential HTTP headers to enhance security.
By incorporating Helmet, you configure several security-related headers
automatically, reducing the need for manual configuration.
Key Security Features with Helmet:
 Content Security Policy (CSP): Restricts resources (scripts, styles,
images) that can be loaded from external sources, preventing XSS and
other attacks.
 X-XSS-Protection: Mitigates XSS vulnerabilities by enabling browser-
side defenses.
 X-Frame-Options: Prevents your application from being rendered within
a frame or iframe, reducing clickjacking risks.
 Strict-Transport-Security (HSTS): Enforces HTTPS communication,
protecting against insecure connections.
 X-Permitted-Cross-Domain-Policies: Disables certain cross-origin
requests if needed.
 Referrer-Policy: Controls how much referrer information is included in
outgoing requests.
 Public-Key-Pins (HPKP): (Optional) Pins public keys to prevent
certificate authority (CA) substitution attacks (advanced).
Implementing Helmet in myNotes:
Installation:

Require Helmet in your Express app:

Additional Security Considerations:


User Authentication and Authorization: Implement mechanisms for user
login, ensuring authorized access to notes.
Input Validation: Sanitize and validate user input to prevent injection attacks
like XSS and SQL injection.
Error Handling: Handle errors gracefully to avoid exposing sensitive
information.
Regular Updates: Keep your development environment, dependencies, and
Node.js version up-to-date to address security vulnerabilities.
Database Security: Secure your database if storing notes there (e.g., user roles,
access control).
Session Management: Follow secure practices when managing user sessions
(e.g., session IDs, expiration).
EXPERIMENT - 9
 TypeScript is an open-source, object-oriented programing language,
which is developed and maintained by Microsoft under the Apache
2 license.
 It was introduced by Anders Hejlsberg, a core member of the
development team of C# language.
 TypeScript is a superset of JavaScript that adds static types to the
language.
 TypeScript compiles down to plain JavaScript, making it compatible with
any browser, host, or operating system. This language is particularly
popular in large-scale applications and among teams seeking to improve
code quality and maintainability.

Type Assignment:

When creating a variable, there are two main ways TypeScript assigns a type:

 Explicit
 Implicit

Explicit Type:
 Explicit type assignment are easier to read and more intentional.
Explicit - writing out the type:
Syntax:
let firstName: string = "Dylan";
Implicit Type:

Implicit - TypeScript will "guess" the type, based on the assigned value:

Syntax:

let firstName = "Dylan";

TypeScript Simple Types:


TypeScript supports some simple types (primitives) as follows.

There are three main primitives in JavaScript and TypeScript.

 boolean - true or false values


 number - whole numbers and floating point values
 string - text values like "TypeScript Rocks"

There are also 2 less common primitives used in later versions of Javascript and
TypeScript.
 bigint - whole numbers and floating point values, but allows larger
negative and positive numbers than the number type.
 symbol are used to create a globally unique identifier.

Special Types:

 any:

any is a type that disables type checking and effectively allows all types to
be used.

EX:

let v: any = true;


v = "string"; // no error as it can be "any" type
Math.round(v); // no error as it can be "any" type

//output:NaN

 Unknown:

TypeScript will prevent unknown types from being used, as shown below
EX:
<script>
let val: unknown;
console.log(val);
val = true;
console.log(val);
val = 7;
val = Math.random();
console.log(val);
val = null;
console.log(val);

</script>
Output:
Undefined
True
7
0.766654
null
 Undefined&null:
undefined and null are types that refer to the JavaScript
primitives undefined and null respectively.
EX:
let y: undefined = undefined;
console.log(typeof y); //undefined
let z: null = null;
console.log(typeof z); //object

Control Flow Statements:

The control statements help users specify the order of execution of the instructions present
in a program.

If, else if, if else if, switch, for, while , do while are some control flow statements.

 if statement:
An if statement executes a statement based on a condition. If the
condition is truthy, the if statement will execute the statements inside its
body:

 if-else statement:
If you want to execute other statements when the condition in the if
statement evaluates to false, you can use the if...else statement:

 switch case:
The following shows the syntax of the switch...case statement:
EX:

Displaying the price of the mobile-based in three different colors . Instead of


using the number in our code, represent them by string values like GoldPlatinum,
PinkGold, SilverTitanium.

FUNCTIONS:
TypeScript, as in most programming languages, a function is a block of reusable
code that performs a specific task when called or invoked. Functions allow you to
encapsulate logic, making your code more modular, easier to understand, and
easier to maintain.

Function Declarations: This is the most common way to declare a function in


TypeScript. It begins with the function keyword followed by the function name,
parameters enclosed in parentheses, and then the function body enclosed in
curly braces {}.

Anonymous function:
In TypeScript, an anonymous function is a function without a name. Instead of
being declared with a function name, it's defined using the function keyword
followed by the parameter list (if any) and the function body. Anonymous
functions are commonly used as callback functions or when a function is only
used once and doesn't need a name.
Functions can also be assigned to variables, creating function expressions.
Function expressions can be named or anonymous.

 Define an arrow function inside the event handler to filter the product array with the
selected product object using the productId received by the function. Pass the selected
product object to the next screen.

Parameter Types and Return Types:


In TypeScript, parameter types and return types are annotations used to specify
the types of parameters a function expects and the type of value it returns.

Parameter types:
Parameter types specify the types of values that a function expects to receive
when it is called. These are declared within the parentheses () after the function
name.

Default Parameter:
You can also provide default values for parameters using the syntax
parameterName: type = defaultValue.

Return Types:
Return types specify the type of value that a function will return after it has
finished executing. This is declared after the parameter list and colon : followed
by the return type.
Number Return Type:

In this example, the add function returns a value of type number. When you call
add(3, 5), it returns the sum of the two numbers, which is of type number.

Void Return Type: A function with a void return type indicates that it does not
return any value.

 Consider that developer needs to declare a function - getMobileByVendor which


accepts string as input parameter and returns the list of mobiles.
Arrow Functions: Arrow functions provide a concise syntax for defining
functions, especially for short anonymous functions. They are denoted by the =>
syntax.

 Consider that developer needs to declare a manufacturer's array holding 4 objects with
id and price as a parameter and needs to implement an arrow function - myfunction to
populate the id parameter of manufacturers array whose price is greater than or equ
Optional and Default Parameters:
Optional Parameters:
In TypeScript, you can mark parameters as optional by appending a ? after the
parameter name. Optional parameters must come after required parameters.

Default Parameters:
You can also provide default values for parameters using the syntax
parameterName: type = defaultValue.

 Declare a function - getMobileByManufacturer with two parameters namely


manufacturer and id, where manufacturer value should passed as Samsung and id
parameter should be optional while invoking the function, if id is passed as 101 then
this function shoul.
EXPERIMENT – 10

10.a Module Name: Rest Parameter


Abstract: This module covers the usage of rest parameters in TypeScript functions. Rest
parameters allow a function to accept an indefinite number of arguments as an array,
providing flexibility in function declarations.
Explanation: Rest parameters are denoted by the three-dot syntax (...parameterName: Type[])
and are used in function declarations to capture multiple arguments into an array. This feature
simplifies function definitions by eliminating the need to specify each argument individually.
Rest parameters are particularly useful when the number of arguments passed to a function is
not known beforehand. By using rest parameters, functions can accept any number of
arguments, making them more flexible and versatile.
Example:
typescriptCopy code
let cart: string[] = []; function addProductsToCart(...products: string[])
{ cart.push(...products); } addProductsToCart('Product1', 'Product2', 'Product3');
console.log('Cart:', cart);
In this example, the addProductsToCart function accepts any number of product names and
adds them to a shopping cart stored in the cart array.

10.b Module Name: Creating an Interface


Abstract: This module focuses on TypeScript interfaces, which define the structure of objects.
Interfaces specify the properties and their types, ensuring consistency and type safety in code.
Explanation: Interfaces in TypeScript define the shape of an object, specifying the properties
and their types that an object must have. They are used to enforce a specific structure for
objects, ensuring that objects conform to a certain pattern.
Interfaces are particularly useful when defining the shape of objects that are used across
multiple parts of a program. By defining an interface, developers can ensure that objects used
in different parts of the program have the same structure, reducing the risk of errors and
improving code maintainability.
Example:
typescriptCopy code
interface Product { productId: number; productName: string; } let products: Product[] = [];
function addProduct(productId: number, productName: string) { let product: Product =
{ productId, productName }; products.push(product); } addProduct(1, 'Product1');
addProduct(2, 'Product2'); addProduct(3, 'Product3'); console.log('Products:', products);
In this example, the Product interface defines the structure of a product object with productId
as a number and productName as a string. The addProduct function adds product objects to
an array of products.

10.c Module Name: Duck Typing


Abstract: This module introduces duck typing in TypeScript, where an object's type is
inferred based on its structure rather than being explicitly defined. Duck typing allows for
more flexibility in TypeScript code.
Explanation: Duck typing in TypeScript refers to the ability to determine an object's type
based on its structure rather than its explicit declaration. This means that TypeScript can infer
the type of an object based on the properties and methods it contains.
Duck typing is particularly useful when working with objects that have similar structures but
are not explicitly related. By relying on the structure of objects rather than their explicit
types, developers can write more flexible and reusable code.
Example:
typescriptCopy code
interface Product { productId: number; productName: string; } let products: Product[] = [];
function addProduct(productId: number, productName: string) { let product: Product =
{ productId, productName }; products.push(product); } addProduct(1, 'Product1');
addProduct(2, 'Product2'); addProduct(3, 'Product3'); console.log('Products:', products);
In this example, TypeScript infers the type of the product object based on its properties
productId and productName, even though there is no explicit type annotation.

10.d Module Name: Function Types


Abstract: This module explores function types in TypeScript, which allow functions to be
treated as values. Function types can be assigned to variables and passed as arguments,
enabling powerful and flexible programming patterns.
Explanation: Function types in TypeScript allow functions to be assigned to variables, passed
as arguments, and returned from other functions. This feature enables functions to be treated
as first-class citizens in TypeScript, allowing for more flexible and expressive code.
Function types are particularly useful when working with higher-order functions, which are
functions that accept other functions as arguments or return functions as results. By using
function types, developers can write more modular and reusable code.
Example:
typescriptCopy code
interface MathFunction { (x: number, y: number): number; } let add: MathFunction; add =
function (x: number, y: number): number { return x + y; } console.log(add(10, 20)); //
Output: 30
In this example, the MathFunction interface defines a function type that takes two numbers
and returns a number. The add variable is then assigned a function that conforms to this type,
and the add function is called with arguments 10 and 20.

These modules provide a comprehensive overview of key TypeScript concepts, including rest
parameters, interfaces, duck typing, and function types.
Experiment - 11
A)Aim:
Declare a productList interface that extends properties from two other declared
interfaces like Category, and Product as well as implementation to create a
variable of this interface type.
Source Code:
interfaceCategory {
categoryName: string;
}
interfaceProduct {
productName: string;
productId: number;
}
interfaceProductListextendsCategory, Product {
list: Array<string>;
}
constproductDetails: ProductList = {
catego
ryNa
me:'G
adget',
produ
ctNam
e:'Mo
bile',
produ
ctId:1
234,
list: ['Samsung', 'Motorola', 'LG']
};
constlistProduct = productDetails.list;
constpname: string = productDetails.productName;
console.log('Product
Name is ' + pname);
console.log('Product
List is ' + listProduct);

Output:

B)Aim:
Consider the Mobile Cart application, Create objects of the Product class and
place them into the productlist array.
Source Code:
interfaceProduct {
displayProductName: (prouctId:
number) =>string;
getProductDetails(): string[];
}
classGadgetimplementsProduct {
getProductDetails(): string[]
{ retur
n
['Sam
sung',
'LG',
'Moto'
];
}
displayProductName(productId: number): string
{if (productId
=== 101)
{ return'Product
Name is
Mobile';
} elseif ( productId === 201)
{ return'Product Name is Tablet';
}
}
getGadget(): string[] {
return ['Mobile', 'Tablet', 'iPad', 'iPod'];
}
}
constgadget: Product
= newGadget();
constproductName: string = gadget.displayProductName(101);
console.log(productName);

Output:

C)Aim:
Declare a class named - Product with the below-mentioned declarations: (i) productId as number
property (ii) Constructor to initialize this value (iii) getProductId method to return the message
"Product id is <id va>"

Source Code:
classProduct {
staticproductpri
ce:string:
productId:numb
er;
constructor(productId:
number) {
this.productId = productId;
}
getProductId(): string {
return'Product id is : ' + this.productId;
}
}
constproduct: Product = newProduct(1234);
console.log(product.ge
tProductId());

Output:

D)Aim:
Create a Product class with 4 properties namely productId, productName,
productPrice, productCategory with private, public, static, and protected access
modifiers and accessing them through Gadget class and its methods.

Source Code:
Class product {
staticproductPrice=150;
privateproductId: number; publicproductName: string; protectedproductCategory: string;
constructor(productId: number, productName ,
productCategory) {
this.productId = productId;
this.productName =
productName;
this.productCategory =
productCategory;
}
product id details
getProductId() {
console.log('The Product id is : ' + this.productId);
}
}
classGadgetextendsProduct {
productCategory property
getProduct(): void {
console.log('Product category is : ' + this.productCategory);
}
}
constg: Gadget = newGadget(1234, 'Mobile', 'SmartPhone');
g.getProduct();
g.getProductId();
console.log('Product name is : ' +
g.productName);
class name console.log('Product price is : $' + Product.productPrice);

Output:

Output:
EXPERIMENT – 12
TYPESCRIPT
Properties and Methods
a) Create a Product class with 4 properties namely productId and methods to
setProductId() and getProductId
In TypeScript, you can create a Product class with properties and methods as required. Here's
a sample implementation that includes a class called Product with one property, productId,
and methods setProductId() and getProductId() to set and get the value of productId,
respectively:

typescript
class Product {
// Private property to store the productId
private productId: number;

// Constructor to initialize the productId with an optional parameter


constructor(productId?: number) {
this.productId = productId || 0; // Default value is set to 0 if not provided
}

// Method to set the productId


public setProductId(productId: number): void {
this.productId = productId;
}

// Method to get the productId


public getProductId(): number {
return this.productId;
}
}
// Example usage:

// Create an instance of the Product class


const product = new Product();

// Set the productId using the setProductId() method


product.setProductId(101);

// Get the productId using the getProductId() method


const id = product.getProductId();
console.log(`Product ID: ${id}`); // Output: Product ID: 101

In the above code:

- The Product class has one private property, productId, which stores the product ID.
- The constructor accepts an optional parameter productId, which can be used to initialize the
productId when an instance is created.
- The setProductId() method takes an argument productId of type number and sets the
productId property of the instance.
- The getProductId() method returns the value of the productId property.
- The example usage creates an instance of the Product class, sets the productId to 101, and
retrieves the value using the getter method.
Module Name: Creating and using Namespaces
12(b) Create a namespace called ProductUtility and place the Product class definition in
it. Import the Product class inside productlist file and use it
In TypeScript, namespaces are a way to organize and encapsulate code within a logical
grouping, similar to modules. By defining a namespace, you can group related classes,
functions, and variables together, providing a clear and structured way to manage your code.

In this example, I'll demonstrate how to create a namespace called ProductUtility and define a
Product class within it. I'll then show how to import the Product class inside a productlist file
and use it.
### Step 1: Define the Namespace and Class

First, create a file named ProductUtility.ts and define the ProductUtility namespace with a
Product class inside it:

typescript
// ProductUtility.ts

// Define the ProductUtility namespace


namespace ProductUtility {
// Define a Product class within the namespace
export class Product {
// Properties of the Product class
quantity: number;
price: number;

// Constructor to initialize the properties


constructor(quantity: number, price: number) {
this.quantity = quantity;
this.price = price;
}

// Method to calculate the total price of the product


calculateTotalPrice(): number {
return this.quantity * this.price;
}
}
}
In this file:

- **Namespace ProductUtility**: The namespace is defined using the namespace keyword. It


groups related code (in this case, the Product class).

- **Product class**: The class is defined within the ProductUtility namespace and includes
properties quantity and price, a constructor to initialize the properties, and a method
calculateTotalPrice() to calculate the total price.

- *Exporting the class*: The Product class is exported from the namespace using the export
keyword, so it can be used in other files.

### Step 2: Import the Class in productlist File

Next, create a file named productlist.ts and import the Product class from the ProductUtility
namespace:

typescript
// productlist.ts

// Import the Product class from the ProductUtility namespace


import Product = ProductUtility.Product;

// Create an instance of the Product class


const product = new Product(3, 20.0);

// Calculate the total price of the product


const totalPrice = product.calculateTotalPrice();

// Log the total price to the console


console.log(`The total price of the product is: $${totalPrice}`);
In this file:

- **Importing the Product class**: The Product class from the ProductUtility namespace is
imported using the import keyword. The syntax import Product = ProductUtility.Product
imports the Product class and renames it to Product for use in this file.

- **Creating an instance of Product**: An instance of the Product class is created with


specified quantity and price.

- *Calculating the total price*: The calculateTotalPrice() method of the Product instance is
used to calculate the total price.

- *Logging the total price*: The calculated total price is logged to the console.

This demonstrates how you can create a namespace in TypeScript to group related code,
define a class within the namespace, and then import and use the class in another file.
Module Name: Creating and using Modules
12(c) Consider the Mobile Cart application which is designed as part of the functions in
a module to calculate the total price of the product using the quantity and price values
and assign it to a totalPrice variable
In TypeScript, you can design a module that calculates the total price of a product using the
quantity and price values and assign it to a totalPrice variable. Here's how you can structure
this module:

First, create a module file named CartModule.ts with the function to calculate the total price
and an interface to represent a product:

// CartModule.ts

// Define an interface for a product with quantity and price properties


export interface Product {
quantity: number;
price: number;
}

// Define a function to calculate the total price of a product


export function calculateTotalPrice(product: Product): number {
// Calculate the total price by multiplying the quantity and price
const totalPrice = product.quantity * product.price;

// Return the calculated total price


return totalPrice;
}
```

In this module:

- **Interface Product**: This interface represents a product with quantity and price
properties.

- **Function calculateTotalPrice**: This function takes a product object as an argument and


calculates the total price by multiplying the quantity with the price. The function returns the
calculated total price.
In TypeScript, modules are a way to encapsulate code into distinct and reusable units,
allowing you to organize your code effectively and manage dependencies between different
parts of your application. The primary purpose of modules is to provide a mechanism to
import and export code so that different components can interact with each other in a clear
and manageable way. This concept helps in separating concerns, improving code readability,
and facilitating code reuse.

1. *What are Modules?*


- Modules are files that encapsulate related code (functions, variables, classes, interfaces,
etc.) into a single, organized unit.
- Modules allow code to be exported from one file and imported into another, enabling you
to use code across different parts of an application.
2. *Exporting Code:*
- In TypeScript, you can use the export keyword to expose code (functions, classes,
variables, etc.) from a module so that it can be used by other modules.
- Exports can be either named exports or default exports.
- *Named Exports*: Allow you to export specific variables, functions, or classes by
name using the export keyword. This allows multiple exports per module.
- *Default Exports*: Allow you to export a single default value from a module using the
export default syntax.

3. *Importing Code:*
- Code from one module can be imported into another using the import keyword.
- When using named exports, you must specify the names of the exported values you want
to import.
- For default exports, you can import the default export using a different name if you wish.

4. *Organizing Code:*
- Modules allow you to organize your code in a logical and meaningful way by grouping
related functions, classes, and other code constructs into separate files.
- This separation of concerns makes the code easier to understand and maintain.

5. *Module Resolution:*
- TypeScript has a module resolution strategy that determines how to find and load
modules. The strategy can include searching the file system and using node_modules
directories to resolve module imports.

6. *Types of Modules:*
- TypeScript supports different module systems:
- *CommonJS*: The module system used by Node.js.
- *ES Modules*: The standard module system used in modern JavaScript.
- TypeScript can compile to either of these module systems, allowing you to use
TypeScript in a variety of runtime environments.
7. *Type Annotations and Interfaces:*
- In addition to exporting functions and classes, you can export interfaces to define the
shape of data structures, such as the Product interface in the CartModule.ts example.
- Type annotations provide type checking and help catch errors at compile time.

Using Modules in a Mobile Cart Application

- For a Mobile Cart application, you might define a module with functions and interfaces
related to shopping cart operations, such as calculating the total price of products.
- By exporting the functions and interfaces from this module, you can import and use them in
other parts of your application, such as the user interface or the checkout process.
- This approach keeps your code organized, modular, and reusable.

Overall, using modules in TypeScript helps improve code organization, maintainability, and
reusability, and facilitates the creation of more complex and scalable applications.
Module Name: What is Generics, What are Type Parameters, Generic Functions,
Generic Constraints
12(d) Create a generic array and function to sort numbers as well as string values
Generics:
Generics in TypeScript allow you to write flexible and reusable code that can operate on a
variety of data types while maintaining type safety. Generics let you abstract over types,
making your code more versatile and adaptable. You can use generics in functions, classes,
and interfaces.

For example, a generic function definition might look like this:

typescript
Copy code
function genericFunction<T>(param: T): T {
return param;
}
Here, T is a type parameter that can represent any data type. This function accepts an
argument of type T and returns the same type T.
Type Parameters
Type parameters are placeholders for actual data types that are provided when you use a
generic function, class, or interface. For example, in the function genericFunction<T>(param:
T): T, the T is a type parameter.

When you use a generic function, class, or interface, you specify the actual type for the type
parameter:

typescript
Copy code
let result = genericFunction<number>(42);
Here, the type parameter T is replaced with the actual type number.

Generic Functions
A generic function allows you to write a function that can work with different types of data.
The function signature includes one or more type parameters. The type parameters are used to
specify the types of the function's arguments and return value.

For example:

typescript
Copy code
function reverseArray<T>(arr: Array<T>): Array<T> {
return arr.reverse();
}

let numbers: Array<number> = [1, 2, 3];


let reversedNumbers = reverseArray(numbers); // [3, 2, 1]

let strings: Array<string> = ['a', 'b', 'c'];


let reversedStrings = reverseArray(strings); // ['c', 'b', 'a']
In the reverseArray function, T is a type parameter that allows the function to operate on
arrays of any type.

Generic Constraints
Generic constraints allow you to specify requirements for the types used in a generic
function, class, or interface. This is done using the extends keyword. The constraint ensures
that the type parameter meets certain conditions, such as implementing a specific interface or
having certain properties.

For example:

typescript
Copy code
interface Comparable {
compareTo(other: any): number;
}

function sortArray<T extends Comparable>(arr: Array<T>): Array<T> {


const copy = [...arr];
return copy.sort((a, b) => a.compareTo(b));
}
In this function, the type parameter T extends the Comparable interface, which means that T
must have a compareTo method. This constraint allows the function to sort arrays of T using
the compareTo method.

Conclusion
Generics in TypeScript are a powerful feature that allow you to write flexible and type-safe
code that can operate on various data types. By using type parameters and generic constraints,
you can ensure that your code behaves correctly and safely with different types of data.

You might also like