Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
16 views236 pages

Mean Stack Technologies Lab Manual

The document outlines various HTML5 elements and attributes, including case insensitivity, DOCTYPE declaration, and metadata elements, while providing practical examples for enhancing a shopping application called IEKart. It includes instructions for creating tables, forms, and media elements, as well as sample code for a homepage and signup page. The document emphasizes the importance of HTML structure and attributes in web development, ensuring functionality and user experience.

Uploaded by

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

Mean Stack Technologies Lab Manual

The document outlines various HTML5 elements and attributes, including case insensitivity, DOCTYPE declaration, and metadata elements, while providing practical examples for enhancing a shopping application called IEKart. It includes instructions for creating tables, forms, and media elements, as well as sample code for a homepage and signup page. The document emphasizes the importance of HTML structure and attributes in web development, ensuring functionality and user experience.

Uploaded by

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

HTML5-Elements, Attributes

HTML Doctype Declaration, Types of Elements,


HTML Elements - Attributes, Metadata Element
Exp. No.:

Date:

Aim:

a) Module Name:Case-insensitivity, Platform-independency, DOCTYPE Declaration, Types of


Elements, HTML Elements - Attributes, Metadata Element.

Include the Meta data element in Homepage.html for providing description as "IEKart's is an
online shopping website that sells goods in retail. This company deals with various categories
like Electronics,Clothing,Accessoriesetc.
b) Module Name:SectioningElements
Enhance the Homepage.html of IEKart's Shopping Application by adding appropriate sectioning
elements.
c) Module Name: Paragraph Element,Division and Span Elements,List Elemen
Make use of appropriate grouping elements such as list itemsto "AboutUs" page of IEKart's
Shopping Application.

d) Module Name: Link Element.


Link "Login", "SignUp" and "Track order" to "Login.html", "SignUp.html" and "Track.html"
page respectively. Bookmark each category to its details of IEKart's Shopping application.
e) Module Name: Character Entities
Add the © symbol in the Home page footer of IEKart's Shopping application.
f) Module Name: HTML5 Global Attributes.
Add the global attributes such as contenteditable, spellcheck, id etc. to enhance the Signup Page
functionality of IEKart's Shopping application.
Software Required:

HTML&Javascript

Dept of CSE, GIET Engineering College, Rajahmundry


HTML5-Elements, Attributes

Theory:
1) Case-Insensitivity in HTML: HTML is not case-sensitive, which means that the tag names and
attribute names can be written in uppercase or lowercase letters, or even a combination of both. For
example, <html>, <HTML>, and <html> are all treated the same by web browsers.
2) Platform-Independence in HTML: HTML is designed to be platform-independent, meaning that
web pages created with HTML should render consistently across different operating systems and
web browsers.
3) DOCTYPE Declaration: A Document Type Declaration, often referred to as a DOCTYPE
declaration, is a statement at the beginning of an HTML document that specifies the version of
HTML being used.
4) Types of HTML Elements: HTML elements can be categorized into several types:
 Block-Level Elements: These create a new block formatting context and typically start
on a new line. Examples include <div>, <p>, <h1>, and <ul>.
 Inline Elements: These do not create a new block formatting context and flow within the
text. Examples include <span>, <a>, <em>, and <strong>.
 Void Elements: These are self-closing elements that do not have a closing tag. Examples
include <img>, <br>, and <input>.
5) HTML Elements - Attributes: HTML elements can have attributes that provide additional
information or modify the behavior of the element. Attributes are defined within the opening tag of
an element. For example: htmlcopycode
<a href="https://www.example.com">Visit Example</a>
6) Metadata Elements: Metadata elements in HTML provide information about the document itself,
rather than the document's content. Some common metadata elements include:
 <meta>: Used to provide metadata such as character encoding, authorship, and viewport
settings.
 <title>: Specifies the title of the web page, which appears in the browser's title bar or
tab.
 <link>: Often used to link to external resources like stylesheets or icon files.
 <base>: Sets the base URL for relative urlswithin the document.

Dept of CSE, GIET Engineering College, Rajahmundry


HTML5-Elements, Attributes

Program
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="description" content="IEKart's is an online shopping website that sells goods in
retail. This company deals with various categories like Electronics, Clothing, Accessories etc.">
<title>IEKart's Shopping Application</title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="#">Electronics</a></li>
<li><a href="#">Clothing</a></li>
<li><a href="#">Accessories</a></li>
<li><a href="Login.html">Login</a></li>
<li><a href="SignUp.html">SignUp</a></li>
<li><a href="Track.html">Track order</a></li>
</ul>
</nav>
</header>
<section>
<h1>About Us</h1>
<ul>
<li>Our mission is to provide high-quality products at reasonable prices.</li>
<li>We offer a wide range of products in various categories.</li>
<li>We are committed to providing excellent customer service.</li>
</ul>
</section>
<section>

Dept of CSE, GIET Engineering College, Rajahmundry


HTML5-Elements, Attributes

<h1>Electronics</h1>
<p>Explore our wide range of electronic products, including smartphones, laptops, and more.</p>
<a href="#">Learn more</a>
</section>
<section>
<h1>Clothing</h1>
<p>Find the latest fashion trends in our clothing collection.</p>
<a href="#">Learn more</a>
</section>
<section>
<h1>Accessories</h1>
<p>Discover a variety of accessories, from watches to jewelry.</p>
<a href="#">Learn more</a>
</section>
<footer>
<p>IEKart's Shopping Application &copy; 2023</p>
</footer>
</body>
</html>

Dept of CSE, GIET Engineering College, Rajahmundry


HTML5-Elements, Attributes

Sample input and Outputs:

Result:
The code for HTML5 Elements is executed successfully without any errors.

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1st edition, SitePoint, Site Point Pty.Ltd., O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1st Edition, DreamTech.
4. An Introduction to Web Design, Programming,1st Edition,PaulSWang ,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)

Dept of CSE, GIET Engineering College, Rajahmundry


HTML5-Creating Elements, Iframe

Creating Table Elements, Form Elements, Media, Iframe


Exp. No.:

Date:

Aim:

a) Module Name: 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.

b) Module Name: Creating Form Elements, Color and Date Pickers, Select and Datalist Elements
Using the form elements create Signup page for IEKart's Shopping application.
c) Module Name:InputElements–Attributes

Enhance Signup page functionalityofIEKart'sShoppingapplicationby adding attributes to input


elements.
d) Module Name:Media,Iframe
Add media content in a frame using audio,video,iframe elements to the Homepage of IEKart's
Shopping application.
Software Required:

HTML&Javascript
Theory:
1) Creating Table Elements:
To create a table in HTML, you use a combination of elements, including <table>, <tr> (table
row), <th> (table header), and <td> (table data).
Here's a basic example of a table structure:
<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>

Dept of CSE, GIET Engineering College, Rajahmundry


HTML5-Creating Elements, Iframe

<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</table>
2) Table Elements:
Colspanand row span Attributes:
Colspan: This attribute is used to specify how many columns a table cell should span horizontally.
Rowspan: This attribute is used to specify how many rows a table cell should span vertically.
Here's an example that demonstrates the use of colspan and rowspan:
<table>
<tr>
<thcolspan="2">Header 1 and 2</th>
</tr>
<tr>
<td>Data 1</td>
<td rowspan="2">Data 2 (spans 2 rows)</td>
</tr>
<tr>
<td>Data 3</td>
</tr>
</table>
3) Table Elements Attributes (border, cellspacing, cellpadding):
Border: Specifies the width of the border around table elements. It is generally used to control the
visibility of the table border.
Cellspacing: Defines the space between cells in a table.
Cellpadding: Specifies the space between the cell content and the cell border.
Example of using these attributes:
<table border="1" cellspacing="10" cellpadding="5">
<tr>
<td>Cell 1</td>

Dept of CSE, GIET Engineering College, Rajahmundry


HTML5-Creating Elements, Iframe

<td>Cell 2</td>
</tr>
<tr>
<td>Cell 3</td>
<td>Cell 4</td>
</tr>
</table>
4) Input Elements - Attributes:
Input elements are used to create forms and accept user input. Common attributes include:
Type: Specifies the type of input element (e.g., text, password, checkbox).
Name: Assigns a name to the input element for form submission.
Value: Sets the initial or default value of the input.
Placeholder: Provides a hint or example text for the user.
Required: Makes the input field mandatory.
Disabled: Disables the input field.
Example of an input element:
<input type="text" name="username" placeholder="Enter your username" required>
5) Media:
Media elements, such as <img>, <audio>, and <video>, allow you to embed media content in web
pages.
Attributes vary depending on the media type, but they often include src (source) and alt
(alternative text for images).
Example for an image:
<imgsrc="image.jpg" alt="A beautiful image">
6)frame:
The <iframe> element is used to embed external content, such as web pages or videos, within
your HTML document. The src attribute specifies the URL of the content to be embedded.
Example:
<iframesrc="https://www.example.com"></iframe>

Dept of CSE, GIET Engineering College, Rajahmundry


HTML5-Creating Elements, Iframe

Program:
Details page:
<! DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="description" content="IEKart's is an online shopping website that sells goods in
retail. This company deals with various categories like Electronics, Clothing, Accessories
etc.">
<title>IEKart's Shopping Application - Product Details</title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="#">Electronics</a></li>
<li><a href="#">Clothing</a></li>
<li><a href="#">Accessories</a></li>
<li><a href="Login.html">Login</a></li>
<li><a href="SignUp.html">SignUp</a></li>
<li><a href="Track.html">Track order</a></li>
</ul>
</nav>
</header>
<main>
<h1>Product Name</h1>
<table border="1" cellspacing="0" cellpadding="5">
<tr>
<td colspan="2">Available Mobile Inventories</td>

Dept of CSE, GIET Engineering College, Rajahmundry


HTML5-Creating Elements, Iframe

</tr>
<tr>
<td rowspan="2">Product Image</td>
<td>Product Description</td>
</tr>
<tr>
<td>Product Price</td>
</tr>
</table>
</main>
<footer>
<p>IEKart's Shopping Application &copy; 2023</p>
</footer>
</body>
</html>
Sign up page:
<! DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="IEKart's is an online shopping website that sells goods in
retail. This company deals with various categories like Electronics, Clothing, Accessories
etc.">
<title>IEKart's Shopping Application - Signup</title>
</head>
<body>
<header>
<nav>
<ul>

Dept of CSE, GIET Engineering College, Rajahmundry


HTML5-Creating Elements, Iframe

<li><a href="#">Electronics</a></li>
<li><a href="#">Clothing</a></li>
<li><a href="#">Accessories</a></li>
<li><a href="Login.html">Login</a></li>
<li><a href="SignUp.html">SignUp</a></li>
<li><a href="Track.html">Track order</a></li>
</ul>
</nav>
</header>
<main>
<h1>Signup</h1>
<form>
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<label for="gender">Gender:</label>
<select id="gender" name="gender" required>
<option value="">Select Gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select><br><br>
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" name="dob" required><br><br>
<label for="favorite-color">FavoriteColor:</label>

Dept of CSE, GIET Engineering College, Rajahmundry


HTML5-Creating Elements, Iframe

<input type="color" id="favorite-color" name="favorite-color"><br><br>


<label for="country">Country:</label>
<input list="countries" name="country">
<datalist id="countries">
<option value="United States">
<option value="Canada">
<option value="Mexico">
<option value="Brazil">
<option value="China">
<option value="India">
<option value="Japan">
<option value="Australia">
<option value="New Zealand">
<option value="South Africa">
</datalist><br><br>
<label for="subscribe-newsletter">Subscribe to Newsletter:</label>
<input type="checkbox" id="subscribe-newsletter" name="subscribe-newsletter"><br><br>
<input type="submit" value="Signup">
</form>
</main>
<footer>
<p>IEKart's Shopping Application &copy; 2023</p>
</footer>
</body>
</html>

Dept of CSE, GIET Engineering College, Rajahmundry


HTML5-Creating Elements, Iframe

Sample input and Outputs:

Result:
The code for HTML5-Attributes,Elements,Media, Iframe is executed successfully without any
errors.

Dept of CSE, GIET Engineering College, Rajahmundry


HTML5-Creating Elements, Iframe

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1st edition, SitePoint, Site Point Pty.Ltd., O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1st Edition, DreamTech.
4. An Introduction to Web Design, Programming,1st Edition,PaulSWang ,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Identifiers

Type of Identifiers
Exp. No.:

Date:

Aim:

Module Name: Type of Identifiers

Write a JavaScript program to find the area of a circle using radius (var and let - reassign and
observe the difference with var and let) and PI (const).

Software Required:

HTML&Javascript
Theory:
In Java, there are several types of identifiers that are used to name various program elements, such
as variables, classes, methods, and more. Here are the main types of identifiers in Java:
1. Class Identifiers:
These are used to name classes in Java. Class identifiers should start with an uppercase letter, and
by convention, they use CamelCase. For example, MyClass is a valid class identifier.
2. Method Identifiers:
These are used to name methods or functions within a class. Method identifiers also start with an
uppercase letter (by convention) and use CamelCase. For example, calculateTotal () is a valid
method identifier.
3. Variable Identifiers
These are used to name variables within methods or classes. Variable identifiers start with a
lowercase letter (by convention) and also use CamelCase. For example, myVariable is a valid
variable identifier.
4. Constant Identifiers:
These are used to name constants, which are typically declared with the final keyword. Constant
identifiers are usually in all uppercase letters with words separated by underscores. For example,
MAX_VALUE is a valid constant identifier.
5. Package Identifiers:

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Identifiers

These are used to name packages in Java. Package identifiers are in lowercase letters and are
typically associated with domain names in reverse order. For example, com.example.myapp is a
valid package identifier.
6. Interface Identifiers:
These are used to name interfaces in Java. Interface identifiers follow the same conventions as
class identifiers, starting with an uppercase letter and using CamelCase. For example, MyInterface
is a valid interface identifier.
7. Enum Identifiers:
These are used to name enumerated types (enums) in Java. Enum identifiers also follow the
conventions of class identifiers, starting with an uppercase letter and using CamelCase. For
example, DayOfWeek is a valid enum identifier.
8. Type Parameter Identifiers:
These are used when defining generic classes or methods. Type parameter identifiers are typically
a single uppercase letter, such as T, E, or K.
9. Label Identifiers:
These are used in conjunction with loops and conditional statements to create labeled statements.
Label identifiers followed by a colon (:) are used to mark specific points in the code.

In javascript, you can find the area of a circle using the formula:
Area = π * r^2
Program:
// using var
var radius = 5;
var pi = Math.PI;
var area = pi * radius * radius;
console.log(area); // output: 78.53981633974483
// reassign radius
radius = 10;
area = pi * radius * radius;
console.log(area); // output: 314.1592653589793
// using let

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Identifiers

let radius2 = 5;
const pi2 = Math.PI;
let area2 = pi2 * radius2 * radius2;
console.log(area2); // output: 78.53981633974483
// reassign radius
radius2 = 10;
area2 = pi2 * radius2 * radius2;
console.log(area2); // output: 314.1592653589793

Sample input and Outputs:

Result:
The code for Type of Identifiers in javascriptis executed successfully without any errors.
References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1st edition, SitePoint, Site Point Pty.Ltd., O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1st Edition, DreamTech.
4. An Introduction to Web Design, Programming,1st Edition,PaulSWang ,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)

Dept of CSE, GIET Engineering College, Rajahmundry


HTML5-Creating Elements, Iframe

Primitive and Non Primitive Data Types


Exp. No.:

Date:

Aim:

Module Name: Primitive and Non Primitive Data Types

Write JavaScript code to display the movie details such as movie name, starring, language, and
ratings. Initialize the variables with values of appropriate types. Use template literals wherever
necessary.

Software Required:

HTML&Javascript
Theory:
Certainly, let's discuss primitive and non-primitive data types in JavaScript:

Primitive Data Types:

Primitive data types in JavaScript are simple, immutable data types that represent single values.
They are stored directly in memory and are passed by value. There are six primitive data types in
JavaScript:

String:

Represents a sequence of characters, enclosed in single (''), double ("") or backticks (``) quotes.
For example:

const name = "John";

Number:

Represents numeric values, including integers and floating-point numbers.

For example:

const age = 25;

Dept of CSE, GIET Engineering College, Rajahmundry


HTML5-Creating Elements, Iframe

Boolean:

Represents a true or false value.

For example:

const isStudent = true;

Undefined:

Represents a variable that has been declared but hasn't been assigned a value yet.

For example:

let undefinedVar;

Null:

Represents the intentional absence of any object value or a variable with no value.

For example:

const emptyValue = null;

Symbol (ES6):

Represents a unique and immutable value used as object property keys.

For example:

const uniqueSymbol = Symbol("description");

Non-Primitive Data Types (Reference Types):

Non-primitive data types, also known as reference types, are more complex and can hold multiple
values. They are stored in memory as references and are passed by reference. The main non-
primitive data type is:

Object:

Represents a collection of key-value pairs, where keys are strings (or Symbols) and values can be
of any data type, including other objects.

Dept of CSE, GIET Engineering College, Rajahmundry


HTML5-Creating Elements, Iframe

For example:

const person = {

name: "Alice",

age: 30,

isStudent: false

};

Arrays and functions are also considered objects in JavaScript.

Understanding the distinction between primitive and non-primitive data types is important when
working with JavaScript because it affects how data is stored, passed, and manipulated in your
programs. Primitive data types are copied by value, while non-primitive data types are copied by
reference, which can lead to differences in behavior when working with them.

In the above example, we initialize the movie details with appropriate values of appropriate types,
such as a string for movieName, an array of strings for starring, a string for language, and a float
for ratings. We then display the movie details using template literals, which allow us to embed
expressions in a string literal. In this way, we can easily interpolate the values of the variables into
the string using ${expression} syntax.

Program:
// initialize movie details

const movieName = "The Dark Knight";

const starring = ["Christian Bale", "Heath Ledger", "Aaron Eckhart"];

const language = "English";

const ratings = 9.0;

// display movie details using template literals

console.log(`Movie Name: ${movieName}`);

console.log(`Starring: ${starring.join(", ")}`);

Dept of CSE, GIET Engineering College, Rajahmundry


HTML5-Creating Elements, Iframe

console.log(`Language: ${language}`);

console.log(`Ratings: ${ratings}`);

Sample input and Outputs:

Result:
The code for primitive and non primitive data types in javascriptis executed successfully without any
errors.
References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1st edition, SitePoint, Site Point Pty.Ltd., O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1st Edition, DreamTech.
4. An Introduction to Web Design, Programming,1st Edition,PaulSWang ,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)

Dept of CSE, GIET Engineering College, Rajahmundry


Operators and Types of Operators

Operators and Types of Operators


Exp. No.:

Date:

Aim:

Module Name: Operators and Types of Operators.

Write JavaScript code to book movie tickets online and calculate the total price, considering the
number of tickets and price per ticket as Rs. 150. Also, apply a festive season discount of 10% and
calculate the discounted amount.
Software Required:

HTML&Javascript
Theory:
In Java, operators are symbols that perform operations on variables and values. They are used to
manipulate data and perform calculations. Java operators can be categorized into several types:

Arithmetic Operators:

+ (Addition)

- (Subtraction)

* (Multiplication)

/ (Division)

% (Modulus, returns the remainder after division)

Example:

int a = 10;

int b = 3;

int sum = a + b;

// sum is 13

Dept of CSE, GIET Engineering College, Rajahmundry


Operators and Types of Operators

Assignment Operators:

= (Assignment)

+= (Add and Assign)

-= (Subtract and Assign)

*= (Multiply and Assign)

/= (Divide and Assign)

%= (Modulus and Assign)

Example:

int x = 5;

x += 3; // x is now 8

Comparison Operators:

== (Equal to)

!= (Not equal to)

< (Less than)

> (Greater than)

<= (Less than or equal to)

>= (Greater than or equal to)

Example:

int num1 = 10;

int num2 = 5;

boolean result = num1 > num2; // result is true

Logical Operators:

&& (Logical AND)

Dept of CSE, GIET Engineering College, Rajahmundry


Operators and Types of Operators

|| (Logical OR)

! (Logical NOT)

Example:

booleanisStudent = true;

booleanhasBooks = false;

booleancanBorrow = isStudent&& !hasBooks; // canBorrow is true

Increment and Decrement Operators:

++ (Increment by 1)

-- (Decrement by 1)

Example:

int count = 5;

count++; // count is now 6

Bitwise Operators (for manipulating individual bits):

& (Bitwise AND)

| (Bitwise OR)

^ (Bitwise XOR)

~ (Bitwise NOT)

<< (Left shift)

>> (Right shift)

>>> (Unsigned right shift)

Example:

int num1 = 5;

int num2 = 3;

Dept of CSE, GIET Engineering College, Rajahmundry


Operators and Types of Operators

int result = num1 &num2;

// result is 1

Conditional (Ternary) Operator:

? : (Conditional operator, shorthand for if-else)

Example:

int age = 18;

String status = (age >= 18) ? "Adult" : "Minor"; // status is "Adult"

Instanceof Operator (for checking object types):

Example:

Object obj = new String("Hello");

booleanisString = obj instanceof String; // isString is true

These operators are fundamental for performing various operations in Java, from basic arithmetic
calculations to making decisions and working with bits at a low level. Understanding how to use
them effectively is crucial for writing Java programs.

Program:
// initialize variables

const pricePerTicket = 150;

const numberOfTickets = 5;

const discount = 0.1;

// calculate total price

let totalPrice = pricePerTicket * numberOfTickets;

// apply discount

let discountAmount = totalPrice * discount;

Dept of CSE, GIET Engineering College, Rajahmundry


Operators and Types of Operators

let discountedPrice = totalPrice - discountAmount;

// display results

console.log(`Number of Tickets: ${numberOfTickets}`);

console.log(`Price per Ticket: Rs. ${pricePerTicket}`);

console.log(`Total Price: Rs. ${totalPrice}`);

console.log(`Discount: ${discount * 100}%`);

console.log(`Discounted Amount: Rs. ${discountAmount}`);

console.log(`Discounted Price: Rs. ${discountedPrice}`);

Sample input and Outputs:

Result:
The code of types of operators in javascript is executed successfully without any errors.

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies,HTML,JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming,
1stEdition,PaulSWang,SandaSKatila, CengageLearning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Statements

Types of Statements
Exp. No.:

Date:

Aim:

Module Name: Types of Statements, Non - Conditional Statements, Types of Conditional


Statements, if Statements, switch Statements

Write a JavaScript code to book movie tickets online and calculate the total price based on the 3
conditions: (a) If seats to be booked are not more than 2, the cost per ticket remains Rs. 150. (b) If
seats are 6 or more, booking is not allowed.
Software Required:

HTML&Javascript
Theory:
In Java, statements are the individual instructions or actions that make up a program. They can be
categorized into non-conditional and conditional statements. Here's an overview of the types of
statements in Java:

Non-Conditional Statements:

Declaration Statements:

Used to declare variables and specify their data types.

Example:

int age; // Declaration statement

Assignment Statements:

Used to assign values to variables.

Example:

age = 25; // Assignment statement

Expression Statements:

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Statements

Used to evaluate expressions and perform actions.

Example:

int result = 2 * 3; // Expression statement

Method Invocation Statements:

Used to call methods or functions.

Example:

System.out.println("Hello, World!"); // Method invocation statement

Conditional Statements:

Conditional statements allow you to execute different code blocks based on specific conditions.

If Statements:

Used for conditional branching.

Executes a block of code if a condition is true.

Example:

if (age >= 18) {

System.out.println("You are an adult.");

If-else Statements:

Executes one block of code if a condition is true and another if it's false.

Example:

if (age >= 18) {

System.out.println("You are an adult.");

} else {

System.out.println("You are a minor.");

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Statements

if-else if-else Statements:

Allows you to test multiple conditions in sequence.

Example:

if (score >= 90) {

System.out.println("A grade.");

} else if (score >= 80) {

System.out.println("B grade.");

} else if (score >= 70) {

System.out.println("C grade.");

} else {

System.out.println("F grade.");

Switch Statements:

Used for multi-way branching based on the value of an expression.

Example:

int dayOfWeek = 3;

switch (dayOfWeek) {

case 1:

System.out.println("Monday");

break;

case 2:

System.out.println("Tuesday");

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Statements

break;

// ...

default:

System.out.println("Invalid day");

These are the fundamental types of statements in Java, and they play a crucial role in controlling
the flow and behavior of your Java programs.

Program:
// Non-conditional statements

const pricePerTicket = 150;

let numTickets = 3;

let totalPrice;

// Types of conditional statements

if (numTickets<= 2) { // if statement

totalPrice = pricePerTicket * numTickets;

} else if (numTickets>= 6) { // if statement

console.log("Booking not allowed for more than 5 tickets.");

} else { // switch statement

switch (numTickets) {

case 3:

totalPrice = pricePerTicket * numTickets * 0.9;

break;

case 4:

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Statements

totalPrice = pricePerTicket * numTickets * 0.8;

break;

case 5:

totalPrice = pricePerTicket * numTickets * 0.75;

break;

default:

console.log("Invalid number of tickets entered.");

// Output the results

if (totalPrice) { // if statement

console.log(`Total price for ${numTickets} tickets is Rs. ${totalPrice}.`);

Sample input and Outputs:

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Statements

Result:
The code for types of statements in javascript is executed successfully without any errors.

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies,HTML,JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming,
1stEdition,PaulSWang,SandaSKatila, CengageLearning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Loops

Types of Loops

Exp. No.:

Date:

Aim:

Module Name: Types of Loops.

Write a JavaScript code to book movie tickets online and calculate the total price based on the 3
conditions: (a) If seats to be booked are not more than 2, the cost per ticket remains Rs. 150. (b) If
seats are 6 or more, booking is not allowed.
Software Required:

HTML&Javascript
Theory:
In Java, there are several types of loops that allow you to repeat a block of code multiple
times. Here are the main types of loops in Java:

For Loop:

Used when you know the number of iterations in advance.

Syntax:

for (initialization; condition; update) {

// Code to be repeated

Example:

for (int i = 0; i< 5; i++) {

System.out.println("Iteration " + i);

While Loop:

Used when you want to repeat a block of code as long as a condition is true.

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Loops

Syntax:

while (condition) {

// Code to be repeated

Example:

int count = 0;

while (count < 3) {

System.out.println("Count: " + count);

count++;

Do-while Loop:

Similar to a while loop but guarantees at least one execution of the block of code, as the
condition is checked after the loop body.

Syntax:

do {

// Code to be repeated

} while (condition);

Example:

int num = 1;

do {

System.out.println("Number: " + num);

num++;

} while (num<= 3);

For-each Loop (Enhanced for Loop):

Used to iterate through elements in arrays or collections (e.g., ArrayLists).

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Loops

Syntax:

for (datatype variable : array/collection) {

// Code to process each element

Example:

int[] numbers = {1, 2, 3, 4, 5};

for (int num : numbers) {

System.out.println("Number: " + num);

These are the primary types of loops in Java. Each type of loop has its own use cases, and you
can choose the one that best suits your programming needs. Loops are essential for repetitive
tasks, and they help make your code more efficient and readable.

Program:
constticketPrice = 150;

let numOfTickets = 0;

let totalPrice = 0;

// Prompt user to enter the number of tickets to book

numOfTickets = prompt("How many tickets would you like to book?");

// Use while loop to ensure the number of tickets entered is valid

while (numOfTickets<= 0 || numOfTickets> 5) {

if (numOfTickets> 5) {

console.log("Sorry, booking is not allowed for more than 5 tickets.");

} else {

console.log("Please enter a valid number of tickets to book.");

numOfTickets = prompt("How many tickets would you like to book?");

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Loops

// Use for loop to calculate the total price of the tickets

for (let i = 1; i<= numOfTickets; i++) {

if (numOfTickets<= 2) {

totalPrice += ticketPrice;

} else {

totalPrice += ticketPrice * 0.9; // 10% festive season discount

console.log(`You have booked ${numOfTickets} tickets at a price of Rs. ${ticketPrice} per


ticket.`);

console.log(`The total price for your booking is Rs. ${totalPrice.toFixed(2)}.`);

Sample input and Outputs:

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Loops

Result:
The code for types of loops in javascript is executed successfully without any errors.

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies,HTML,JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming,
1stEdition,PaulSWang,SandaSKatila, CengageLearning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)

Dept of CSE, GIET Engineering College, Rajahmundry


Functions

Fuctions,Declaring and Invoking Functions


Exp. No.:

Date:

Aim:

Module Name: Types of Functions, Declaring and Invoking Function, Arrow

Function, Function Parameters, Nested Function, Built-in Functions, Variable Scope in Functions
Write a JavaScript code to book movie tickets online and calculate the total price based on the 3
conditions: (a) If seats to be booked are not more than 2, the cost per ticket remains Rs. 150. (b) If
seats are 6 or more, booking is not allowed.

Software Required:

HTML&Javascript
Theory:

It appears there's a slight misunderstanding. Java and javascript (often abbreviated as JS) are two
distinct programming languages. While they share similar names, they have different syntax,
features, and purposes. I'll provide information related to javascript, as it seems you are looking for
javascript-related concepts.

Types of Functions in javascript:

Function Declaration:

Declares a named function that can be called later in your code.

Syntax:

function functionName(parameters) {

// Code to be executed

Function Expression:

Dept of CSE, GIET Engineering College, Rajahmundry


Functions

Assigns an anonymous function to a variable or constant.

Syntax:

constfunctionName = function(parameters) {

// Code to be executed

};

Arrow Function (ES6):

A concise way to write functions, often used for anonymous functions.

Syntax:

constfunctionName = (parameters) => {

// Code to be executed

};

Declaring and Invoking Functions in JavaScript:

// Function Declaration

function greet(name) {

console.log("Hello, " + name);

// Function Expression

const add = function(a, b) {

return a + b;

};

// Arrow Function

Dept of CSE, GIET Engineering College, Rajahmundry


Functions

const multiply = (x, y) => x * y;

// Invoking Functions

greet("Alice"); // Invoking greet function

const sum = add(3, 5); // Invoking add function

const product = multiply(2, 4); // Invoking multiply function

Function Parameters:

Functions can accept parameters (inputs) that are used in the function's code.

function greet(name) {

console.log("Hello, " + name);

greet("Bob"); // Outputs: "Hello, Bob"

Nested Function:

In JavaScript, you can define a function within another function. This is called a nested or
inner function.

function outerFunction() {

console.log("Outer function");

function innerFunction() {

console.log("Inner function");

innerFunction();

Dept of CSE, GIET Engineering College, Rajahmundry


Functions

outerFunction();

// Outputs:

// "Outer function"

// "Inner function"

Built-in Functions:

JavaScript provides a wide range of built-in functions (e.g., console.log(), parseInt(),


Math.random()) that perform various tasks. These functions are available for use without
needing to define them yourself.

Variable Scope in Functions:

Variables declared within a function are scoped to that function and are not accessible from
outside. This is known as function-level or local scope. Variables declared outside of any
function have global scope and can be accessed throughout the code.

function localScopeExample() {

constlocalVar = "I'm local!";

console.log(localVar); // Accessible within the function

localScopeExample();

console.log(localVar); // Error - localVar is not defined globally

It's important to understand the differences in scope to avoid naming conflicts and manage
variable accessibility in your code.

Program:
const TICKET_PRICE = 150; // cost per ticket

const DISCOUNT_PERCENTAGE = 10; // festive season discount percentage

Dept of CSE, GIET Engineering College, Rajahmundry


Functions

function bookTickets(numSeats) {

let totalPrice = 0;

function calculatePrice(numSeats) {

let price = 0;

if (numSeats<= 2) {

price = numSeats * TICKET_PRICE;

} else if (numSeats>= 6) {

console.log("Sorry, booking is not allowed for 6 or more seats.");

return;

} else {

price = numSeats * TICKET_PRICE * (1 - DISCOUNT_PERCENTAGE / 100);

return price;

totalPrice = calculatePrice(numSeats);

console.log(`Total price for ${numSeats} seats: Rs. ${totalPrice}`);

// Example usage

bookTickets(2);

// Output: Total price for 2 seats: Rs. 300

bookTickets(7);

Dept of CSE, GIET Engineering College, Rajahmundry


Functions

// Output: Sorry, booking is not allowed for 6 or more seats.

bookTickets(4);

// Output: Total price for 4 seats: Rs. 540

Sample input and Outputs:

Result:
The code for types of functions in java script is executed successfully without any errors.

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies,HTML,JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming,
1stEdition,PaulSWang,SandaSKatila, CengageLearning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)

Dept of CSE, GIET Engineering College, Rajahmundry


Creating and Inheriting Classes

Creating and Inheriting Classes


Exp. No.:

Date:

Aim:

Module Name: WorkingWithClasses,CreatingandInheritingClasses.

Create an Employee class extending from a base class Person.Hints:


(i) Create a classPersonwithnameandageasattributes.
(ii) Addaconstructor to initialize the values
(iii) CreateaclassEmployee textendingPersonwithadditionalattributesrole
Software Required:

HTML&Javascript
Theory:
In Java, classes are the blueprint for creating objects. You can create your own classes and also
inherit from existing classes to reuse and extend their functionality. Here's an overview of
working with classes, creating classes, and inheriting classes in Java:

Creating Classes:

To create a class in Java, you typically follow this structure:

Public class classname {

// Fields (instance variables)

// Constructors

// Methods

Public:

Access modifier indicating that the class is accessible from any other class.

Dept of CSE, GIET Engineering College, Rajahmundry


Creating and Inheriting Classes

Classname: The name of your class, which should start with an uppercase letter.

Here's an example of creating a simple class called Person:

Public class Person {

// Fields (instance variables)

String name;

Int age;

// Constructor

Public Person(String name, int age) {

This.name = name;

This.age = age;

// Method

Public void sayhello() {

System.out.println("Hello, my name is " + name);

Creating Objects (Instances of a Class):

To use a class, you create objects or instances of that class using the new keyword:

Person person1 = new Person("Alice", 30);

Person person2 = new Person("Bob", 25);

Inheriting Classes (Inheritance):

Dept of CSE, GIET Engineering College, Rajahmundry


Creating and Inheriting Classes

Inheritance allows you to create a new class that is a modified version of an existing class,
inheriting its attributes and methods. The new class is called a subclass, and the existing class
is called a superclass.

Here's an example of inheriting from a class Person to create a subclass Student:

Public class Student extends Person {

String studentid;

Public Student(String name, int age, String studentid) {

Super(name, age); // Call the constructor of the superclass (Person)

This.studentid = studentid;

Public void study() {

System.out.println(name + " is studying.");

In this example, Student inherits the name and age fields and the sayhello() method from the
Person class. It also has an additional field, studentid, and a study() method.

Using Inherited Classes:

You can create instances of the subclass and use its methods:

Student student1 = new Student("Charlie", 22, "S12345");

Student1.sayhello(); // Inherited from Person

Student1.study(); // Student-specific method

// You can also access inherited fields and methods

Dept of CSE, GIET Engineering College, Rajahmundry


Creating and Inheriting Classes

System.out.println(student1.name); // Access the name field

In this way, you can create and inherit classes to organize and extend your code in Java,
following the principles of object-oriented programming.

Program:
class Person {

constructor(name, age) {

this.name = name;

this.age = age;

}}

class Employee extends Person {

constructor(name, age, role) {

super(name, age);

this.role = role;

}}

Sample input and Outputs:

Dept of CSE, GIET Engineering College, Rajahmundry


Creating and Inheriting Classes

Result:
The code for creating and inheriting classes in javascript is executed successfully without any
errors.

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies,HTML,JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming,
1stEdition,PaulSWang,SandaSKatila, CengageLearning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)

Dept of CSE, GIET Engineering College, Rajahmundry


Events and Handlers

Events and Handlers


Exp. No.:

Date:

Aim:

Module Name: In-built Events and Handlers.

Write a JavaScript code to book movie tickets online and calculate the total price based on the 3
conditions: (a) If seats to be booked are not more than 2, the cost per ticket remains Rs. 150. (b) If
seats are 6 or more, booking is not allowed.
Software Required:

HTML&Javascript
Theory:
In the context of programming and software development, "in-built events and handlers" typically
refer to events and event handlers that are part of a particular programming framework, library, or
platform. These events and handlers allow you to respond to user interactions or system events
within your application. The specifics can vary depending on the technology or framework you
are using. Here's a general overview:

Events:

Events represent occurrences or interactions that happen within a software application. These
events can be triggered by user actions, like clicking a button, moving the mouse, typing on the
keyboard, or system-related events like a timer reaching a specific interval. Events can also be
custom-defined within your code to signal specific occurrences.

Event Handlers:

Event handlers are functions or methods that are executed in response to a specific event
occurring. They are responsible for defining what should happen when the event takes place.
Event handlers are associated with particular events, and when the event occurs, the associated
handler is called.

Dept of CSE, GIET Engineering College, Rajahmundry


Events and Handlers

In-Built Events:

These are events that are predefined or provided by the programming framework, library, or
platform you are using. Examples include user interface (UI) events like button clicks in a
graphical user interface (GUI) framework, mouse events, keyboard events, and system-level
events like timers or network events.

Custom Events:

In addition to in-built events, you can create custom events in many programming environments.
These events allow you to define and trigger your own events when specific conditions or actions
occur in your application.

Here's an example in javascript using the Document Object Model (DOM), which is a common
place to work with events and event handlers in web development:

// Add an event listener to a button element

Const button = document.getelementbyid('mybutton');

Button.addeventlistener('click', function() {

// This function is the event handler

Alert('Button clicked!');

});

In this example:

'Click' is an in-built event associated with the button element.

Addeventlistener is a method that allows you to attach an event handler function to the button's
click event.

The anonymous function inside addeventlistener is the event handler, which displays an alert
when the button is clicked.

Dept of CSE, GIET Engineering College, Rajahmundry


Events and Handlers

The specific events and how you handle them may vary depending on the programming language,
framework, or library you are using. Understanding events and event handlers is crucial for
building interactive and responsive software applications.

Program:
Html code

<div>

<label for="num-tickets">Number of tickets:</label>

<input type="number" id="num-tickets">

<button id="book-btn">Book Tickets</button>

</div>

Java script

constticketPrice = 150;

function calculateTotalPrice(numTickets) {

let totalPrice;

if (numTickets> 2 &&numTickets< 6) {

totalPrice = numTickets * ticketPrice * 0.9;

} else if (numTickets<= 2) {

totalPrice = numTickets * ticketPrice;

} else {

alert("Sorry, booking more than 5 tickets is not allowed.");

return totalPrice;

Dept of CSE, GIET Engineering College, Rajahmundry


Events and Handlers

function handleBookBtnClick() {

constnumTicketsInput = document.getElementById("num-tickets");

constnumTickets = parseInt(numTicketsInput.value);

consttotalPrice = calculateTotalPrice(numTickets);

if (totalPrice) {

alert(`Total price: Rs. ${totalPrice}`);

constbookBtn = document.getElementById("book-btn");

bookBtn.addEventListener("click", handleBookBtnClick);

Sample input and Outputs:

Result:
The code for In-builtEventsandHandlers in javascript is executed successfully without any errors.

Dept of CSE, GIET Engineering College, Rajahmundry


Events and Handlers

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies,HTML,JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming,
1stEdition,PaulSWang,SandaSKatila, CengageLearning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Objects

Objects, Types of Objects


Exp. No.:

Date:

Aim:

Module Name: Working with Objects, Types of Objects, Creating Objects, Combining and
cloning Objects using Spread operator, Destructuring Objects, Browser Object Model, Document
Object Model.

If a user clicks on the given link, they should see an empty cone a different heading, and a
different message and a different background color. If user clicks again, they should see a re-filled
cone, a different heading, a different message, and a differ.

Software Required:

HTML&Javascript
Theory:
It appears there might be some confusion. The topics you mentioned, such as "Working with
Objects," "Combining and cloning Objects using Spread operator," "Destructuring Objects,"
"Browser Object Model," and "Document Object Model," are typically associated with JavaScript,
not Java.

In JavaScript, these concepts pertain to the manipulation and usage of objects and the interaction
with the Document Object Model (DOM) in web development. Let's briefly explain them in the
context of JavaScript:

Working with Objects:

JavaScript is an object-oriented language, and objects are fundamental data structures.

Objects can store data as key-value pairs and methods (functions).

You can create, modify, and access object properties.

Types of Objects:

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Objects

In JavaScript, there are several built-in object types, including:

Object: The most fundamental object type.

Array: A special object type for storing ordered collections of values.

Function: Objects that are also callable as functions.

Date: For working with dates and times.

Math: Provides mathematical functions and constants.

String: Represents text.

Boolean: Represents true or false values.

Number: Represents numeric values.

Creating Objects:

You can create objects using object literals, constructors, or classes (in modern JavaScript).

// Using an object literal

const person = {

name: 'Alice',

age: 30

};

// Using a constructor

function Person(name, age) {

this.name = name;

this.age = age;

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Objects

const person = new Person('Alice', 30);

Combining and Cloning Objects using the Spread Operator:

The spread operator (...) can be used to combine and clone objects.

const obj1 = { a: 1, b: 2 };

const obj2 = { b: 3, c: 4 };

const combined = { ...obj1, ...obj2 }; // Combine

const cloned = { ...obj1 }; // Clone

Destructuring Objects:

Destructuring allows you to extract values from objects and assign them to variables easily.

const person = { name: 'Bob', age: 25 };

const { name, age } = person; // Destructuring

console.log(name); // Outputs: 'Bob'

Browser Object Model (BOM):

The Browser Object Model provides access to the browser's window and its components, such as
location, history, and navigator.

It is used for browser-related interactions like opening new windows, controlling the browser, and
manipulating the URL.

Document Object Model (DOM):

The DOM represents the structured content of a web page, allowing you to interact with and
manipulate HTML and XML documents.

It provides methods and properties to access, modify, and update document elements.

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Objects

Please note that these concepts are specific to JavaScript, not Java. Java is a different
programming language with its own set of concepts and libraries.

Program:
HTML:

<!DOCTYPE html>

<html>

<head>

<title>Ice Cream Cone</title>

<style>

body {

background-color: #f0f0f0;

.cone {

width: 150px;

height: 300px;

margin: 50px auto;

background-color: white;

border-radius: 50% 50% 0 0;

position: relative;

.scoop {

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Objects

width: 120px;

height: 120px;

background-color: #ffa500;

border-radius: 50%;

position: absolute;

top: -60px;

left: 15px;

transition: all 0.5s;

.scoop.filled {

height: 150px;

top: -90px;

h1 {

text-align: center;

font-size: 36px;

margin-top: 0;

color: #333;

p{

text-align: center;

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Objects

font-size: 24px;

color: #666;

.btn {

display: block;

width: 100px;

height: 40px;

margin: 20px auto;

background-color: #4caf50;

color: white;

text-align: center;

line-height: 40px;

border-radius: 5px;

cursor: pointer;

</style>

</head>

<body>

<div class="cone">

<div class="scoop"></div>

</div>

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Objects

<h1>Ice Cream Cone</h1>

<p>Click the button to fill the cone</p>

<div class="btn" onclick="toggleScoop()">Fill Cone</div>

<script src="app.js"></script>

</body>

</html>

JavaScript (app.js):

let filled = false;

let btn = document.querySelector('.btn');

let scoop = document.querySelector('.scoop');

let heading = document.querySelector('h1');

let message = document.querySelector('p');

let body = document.querySelector('body');

function toggleScoop() {

filled = !filled;

scoop.classList.toggle('filled');

if (filled) {

heading.innerText = 'Yum, Ice Cream!';

message.innerText = 'Enjoy your ice cream cone!';

body.style.backgroundColor = '#ffa500';

btn.innerText = 'Empty Cone';

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Objects

} else {

heading.innerText = 'Ice Cream Cone';

message.innerText = 'Click the button to fill the cone';

body.style.backgroundColor = '#f0f0f0';

btn.innerText = 'Fill Cone';

Sample input and Outputs:

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Objects

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Objects

Result:
The code for Types of Objects in javascript is executed successfully without any errors.

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies,HTML,JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming,
1stEdition,PaulSWang,SandaSKatila, CengageLearning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)

Dept of CSE, GIET Engineering College, Rajahmundry


Array Methods

Array Methods
Exp. No.:

Date:

Aim:

Module Name: Creating Arrays, Destructuring Arrays, Accessing Arrays, Array Methods .

Create an array of objects having movie details. The object should include the movie name,
starring, language, and ratings. Render the details of movies on the page using the array.

Software Required:

HTML&Javascript
Theory:
In Java, arrays are used to store collections of elements of the same data type. Here's how you can
work with arrays in Java:

Creating Arrays:

You can create arrays in Java using the following syntax:

// Declare an array of integers

int[] numbers;

// Initialize an array with values

int[] evenNumbers = {2, 4, 6, 8, 10};

// Initialize an array with a specified size

int[] oddNumbers = new int[5];

Destructuring Arrays:

In Java, there's no direct concept of "destructuring" arrays like in some other languages. You
typically access array elements by index, rather than destructure them into individual variables.
For example:

Dept of CSE, GIET Engineering College, Rajahmundry


Array Methods

int[] numbers = {1, 2, 3, 4, 5};

int thirdNumber = numbers[2]; // Access the third element (index 2)

Accessing Arrays:

You can access elements of an array by their index, which starts at 0 for the first element. For
example:

int[] numbers = {1, 2, 3, 4, 5};

int firstNumber = numbers[0]; // Access the first element

int secondNumber = numbers[1]; // Access the second element

Array Methods:

Java provides various methods and operations for working with arrays. Some common array
methods include:

Length Property: To get the length (number of elements) of an array.

int[] numbers = {1, 2, 3, 4, 5};

int length = numbers.length; // Get the length (returns 5)

Sorting: You can use the Arrays.sort() method to sort an array in ascending order.

int[] numbers = {5, 2, 8, 1, 4};

Arrays.sort(numbers); // Sort the array

Searching: You can use methods like Arrays.binarySearch() to search for an element in a sorted
array.

int[] numbers = {1, 2, 3, 4, 5};

int index = Arrays.binarySearch(numbers, 3); // Search for 3 (returns 2)

Dept of CSE, GIET Engineering College, Rajahmundry


Array Methods

Copying Arrays: To copy the contents of one array to another, you can use System.arraycopy() or
other methods.

int[] source = {1, 2, 3};

int[] destination = new int[source.length];

System.arraycopy(source, 0, destination, 0, source.length);

Iterating through Arrays: You can use loops (e.g., for or foreach) to iterate through array elements.

int[] numbers = {1, 2, 3, 4, 5};

for (int i = 0; i<numbers.length; i++) {

System.out.println(numbers[i]);

These are some basic operations you can perform with arrays in Java. Arrays in Java have a fixed
size, and you typically need to use other data structures like ArrayList if you need a dynamic,
resizable collection.

Program:
const movies = [

name: 'The Godfather',

starring: ['Marlon Brando', 'Al Pacino', 'James Caan'],

language: 'English',

rating: 9.2

},

Dept of CSE, GIET Engineering College, Rajahmundry


Array Methods

name: 'Parasite',

starring: ['Song Kang-ho', 'Lee Sun-kyun', 'Cho Yeo-jeong'],

language: 'Korean',

rating: 8.6

},

name: 'La La Land',

starring: ['Ryan Gosling', 'Emma Stone', 'John Legend'],

language: 'English',

rating: 8.0

},

name: 'Inception',

starring: ['Leonardo DiCaprio', 'Joseph Gordon-Levitt', 'Ellen Page'],

language: 'English',

rating: 8.8

},

name: 'Spirited Away',

starring: ['Rumi Hiiragi', 'Miyu Irino', 'Mari Natsuki'],

language: 'Japanese',

Dept of CSE, GIET Engineering College, Rajahmundry


Array Methods

rating: 8.6

];

To render these movie details on a webpage, you could create an HTML element to hold the
movie data, and then loop over the array of movies to create an element for each one. Here's an
example implementation using JavaScript

<!DOCTYPE html>

<html>

<head>

<title>Movie Details</title>

</head>

<body>

<div id="movies"></div>

<script>

const movies = [

name: 'The Godfather',

starring: ['Marlon Brando', 'Al Pacino', 'James Caan'],

language: 'English',

rating: 9.2

},

Dept of CSE, GIET Engineering College, Rajahmundry


Array Methods

name: 'Parasite',

starring: ['Song Kang-ho', 'Lee Sun-kyun', 'Cho Yeo-jeong'],

language: 'Korean',

rating: 8.6

},

name: 'La La Land',

starring: ['Ryan Gosling', 'Emma Stone', 'John Legend'],

language: 'English',

rating: 8.0

},

name: 'Inception',

starring: ['Leonardo DiCaprio', 'Joseph Gordon-Levitt', 'Ellen Page'],

language: 'English',

rating: 8.8

},

name: 'Spirited Away',

starring: ['Rumi Hiiragi', 'Miyu Irino', 'Mari Natsuki'],

language: 'Japanese',

Dept of CSE, GIET Engineering College, Rajahmundry


Array Methods

rating: 8.6

];

const moviesContainer = document.getElementById('movies');

movies.forEach(movie => {

const movieElement = document.createElement('div');

movieElement.innerHTML = `

<h2>${movie.name}</h2>

<p>Starring: ${movie.starring.join(', ')}</p>

<p>Language: ${movie.language}</p>

<p>Rating: ${movie.rating}</p>

`;

moviesContainer.appendChild(movieElement);

});

</script>

</body>

</html>

Dept of CSE, GIET Engineering College, Rajahmundry


Array Methods

Sample input and Outputs:

Result:
The code for array method in javascript is executed successfully without any errors.

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies,HTML,JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming,
1stEdition,PaulSWang,SandaSKatila, CengageLearning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)

Dept of CSE, GIET Engineering College, Rajahmundry


Asynchronous

Asynchronous Programming, Callbacks, Promises, Async and Await

Exp. No.:

Date:

Aim:

Module Name: Creating Introduction to Asynchronous Programming, Callbacks, Promises,


Async and Await, Executing Network Requests using Fetch API.

Simulate a periodic stock price change and display on the console. Hints: (i) Create a method
which returns a random number - use Math.random, floor and other methods to return a rounded
value. (ii) Invoke the method for every three seconds and stop.
Software Required:

HTML&Javascript
Theory:
Asynchronous programming in Java typically involves using concepts like threads, concurrency,
and callbacks. It's important to note that Java is not primarily designed for asynchronous
programming in the same way as JavaScript or languages with built-in asynchronous features.
However, Java provides mechanisms for handling asynchronous operations using libraries and
frameworks. Here's an overview of asynchronous programming concepts in Java:

Asynchronous Programming:Asynchronous programming allows tasks to be executed


concurrently without blocking the main program's execution. This is useful for tasks such as
network requests, file I/O, and handling user input without freezing the application.

Callbacks:Callbacks are functions or pieces of code that are passed as arguments to other
functions. They are executed when a specific task is completed. Callbacks are commonly used in
Java for handling asynchronous operations. For example, in Java Swing or JavaFX for GUI
applications, you might use event listeners as callbacks to respond to user interactions.

Dept of CSE, GIET Engineering College, Rajahmundry


Asynchronous Programming

Promises:Promises are not a native concept in Java but are commonly used in JavaScript and
some JavaScript-based frameworks. Promises provide a way to handle asynchronous operations
more cleanly, allowing you to attach success and error handlers to a task and handle the results or
errors when the task is completed.

Async and Await (Java 8+): Java introduced the CompletableFuture class in Java 8, which
allows you to write asynchronous code in a more synchronous manner using methods like
thenApply, thenCompose, and whenComplete. While not the same as async and await in
JavaScript, CompletableFuture provides similar functionality for asynchronous programming.

Program:
// Define a function to return a random number between min and max

function getRandomNumber(min, max) {

return Math.floor(Math.random() * (max - min + 1)) + min;

// Define a function to simulate a stock price change

function simulateStockPriceChange() {

const currentPrice = 100; // Set the initial price

const minChange = -5; // Set the minimum price change as a percentage

const maxChange = 5; // Set the maximum price change as a percentage

// Calculate the new price based on a random price change

const priceChangePercent = getRandomNumber(minChange, maxChange);

const priceChangeAmount = currentPrice * (priceChangePercent / 100);

const newPrice = currentPrice + priceChangeAmount;

// Log the new price to the console

Dept of CSE, GIET Engineering College, Rajahmundry


Asynchronous Programming

console.log(`Current stock price: $${newPrice.toFixed(2)}`);

// Define a function to start the periodic updates

function startPeriodicUpdates(interval) {

const intervalId = setInterval(simulateStockPriceChange, interval);

setTimeout(() => {

clearInterval(intervalId);

console.log('Updates stopped');

}, 10000); // Stop updates after 10 seconds

}// Start periodic updates every 3 seconds

startPeriodicUpdates(3000);

Sample input and Outputs:

Dept of CSE, GIET Engineering College, Rajahmundry


Asynchronous Programming

Result:
The code for Asynchronous Programming, Callbacks, Promisesinjavascript is executed
successfully without any errors.

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies,HTML,JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming,
1stEdition,PaulSWang,SandaSKatila, CengageLearning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)

Dept of CSE, GIET Engineering College, Rajahmundry


Modules

Creating Modules, Consuming Modules


Exp. No.:

Date:

Aim:

Module Name: Creating Modules, Consuming Modules.

Validatetheuserbycreatingaloginmodule.
Hints:
(i)Createafilelogin.JswithaUserclass.
(ii)Createavalidatemethodwithusernameandpasswordasarguments.
(iii) Iftheusernameand password areequalitwill return"LoginSuccessful".
Software Required:

HTML&Javascript
Theory:
In JavaScript, modules allow you to organize your code into reusable and encapsulated units.
Modules help prevent naming conflicts, promote code separation, and improve maintainability.
There are two primary aspects to consider when working with modules in JavaScript: creating
modules and consuming modules.

Creating Modules:

To create a module in JavaScript, you typically encapsulate your code in a separate file and export
the functions, objects, or variables that you want to make available to other parts of your
application. You can use either the CommonJS module system (Node.js) or the ES6 module
system (browsers and modern Node.js).

Using CommonJS (Node.js):

math.js:

// Exporting a function

Dept of CSE, GIET Engineering College, Rajahmundry


Using Node.js

exports.add = function (a, b) {

return a + b;

};

// Exporting a variable

exports.PI = 3.14159265359;

Using ES6 Modules (Browser or Node.js with ES6 support):

math.js:

// Exporting a function

export function add(a, b) {

return a + b;

// Exporting a variable

export const PI = 3.14159265359;

Consuming Modules:

Once you've created a module, you can import and use its exported values in other parts of your
code.

Using CommonJS (Node.js):

main.js:

const math = require('./math'); // Import the math module

console.log(math.add(2, 3)); // Use the exported function

console.log(math.PI); // Use the exported variable

Dept of CSE, GIET Engineering College, Rajahmundry


Using Node.js

Using ES6 Modules (Browser or Node.js with ES6 support):

main.js:

import { add, PI } from './math'; // Import specific values from the math module

console.log(add(2, 3)); // Use the exported function

console.log(PI); // Use the exported variable

Using ES6 Modules with Default Exports:

You can also have default exports in ES6 modules:

math.js:

// Exporting a function as the default export

export default function add(a, b) {

return a + b;

main.js:

import add from './math'; // Import the default export

console.log(add(2, 3)); // Use the default export

Browser Support:

Note that ES6 module syntax is now widely supported in modern browsers, but for older
browsers, you might need to use a bundler like Webpack or a transpiler like Babel to convert ES6
module code to a format that works in all browsers.

Dept of CSE, GIET Engineering College, Rajahmundry


Using Node.js

These are the basic principles of creating and consuming modules in JavaScript. Modules help
you structure your codebase and promote reusability, making your applications more manageable
and maintainable.

Program:

class User {

constructor(username, password) {

this.username = username;

this.password = password;

function validate(username, password) {

// Check if the username and password match

if (username === password) {

return "Login Successful";

} else {

return "Login Failed";

module.exports = {

User,

validate

};

Dept of CSE, GIET Engineering College, Rajahmundry


Using Node.js

const { User, validate } = require('./login');

// Create a new user and validate their credentials

const user = new User('john', 'password123');

console.log(validate(user.username, user.password)); // Login Failed

const user2 = new User('jane', 'jane');

console.log(validate(user2.username, user2.password)); // Login Successful

Sample input and Outputs:

Result:
The code for Creating and Consuming Modules in javascript is executed successfully without any
errors.

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies,HTML,JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming,
1stEdition,PaulSWang,SandaSKatila, CengageLearning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)

Dept of CSE, GIET Engineering College, Rajahmundry


Using Node.js

How to use Node.js


Exp. No.:

Date:

Aim:

Module Name: How to use Node.js.

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

Software Required:

HTML, Javascript, Node.js


Theory:

To use Node.js, you need to follow these steps:

Install Node.js:

If you haven't already, you'll need to install Node.js on your computer. Node.js is available for
various operating systems, including Windows, macOS, and Linux. You can download the
installer from the official Node.js website:

Node.js Downloads

After installation, open your terminal (command prompt on Windows) and type the following to
verify that Node.js and npm (Node Package Manager) are installed:

node -v

npm -v

You should see the versions of Node.js and npm displayed if the installation was successful.

Create a Node.js Application:

You can start by creating a directory for your Node.js application and navigating to it in your
terminal.

Dept of CSE, GIET Engineering College, Rajahmundry


Using Node.js

mkdir my-node-app

cd my-node-app

Initialize a Node.js Project:

To manage your Node.js project and its dependencies, use the npminit command. This command
will guide you through creating a package.json file that contains information about your project
and its dependencies.

npminit

Follow the prompts to set up your project.

Create a Node.js Script:

In your project directory, create a JavaScript file (e.g., app.js) that contains your Node.js code.
You can use any code editor or IDE of your choice to create and edit the file.

For example, create a simple "Hello, Node.js!" script in app.js:

console.log("Hello, Node.js!");

Run Your Node.js Application:

You can execute your Node.js script by running it with the node command followed by the script
filename. In your project directory:

node app.js

You should see the output "Hello, Node.js!" in your terminal.

Install Dependencies:

If your Node.js application requires external packages or libraries, you can install them using
npm. For example, to install the popular express web framework:

npm install express

Dept of CSE, GIET Engineering College, Rajahmundry


Using Node.js

This command will download and install the express package, and it will be added to your
project's package.json file as a dependency.

Create More Complex Applications:

Node.js is a versatile platform that can be used for a wide range of applications, including web
servers, APIs, command-line tools, and more. As you become familiar with Node.js, you can
explore its ecosystem and build more complex applications using libraries and frameworks that
suit your needs.

That's a basic overview of how to use Node.js to create and run JavaScript applications.
Remember that Node.js is highly extensible, and you can leverage a vast ecosystem of packages
and tools available through npm to simplify your development tasks.

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)

Dept of CSE, GIET Engineering College, Rajahmundry


Webserver in Node.js

Create a web server in Node.js


Exp. No.:

Date:

Aim:

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.

Software Required:

HTML, Javascript, Node.js


Theory:

Creating a simple web server in Node.js is relatively straightforward using the built-in http
module. Below is a step-by-step guide to create a basic web server that listens for incoming HTTP
requests and responds with a "Hello, World!" message.

Create a New Directory:

First, create a new directory for your Node.js web server project:

mkdir my-node-server

cd my-node-server

Initialize a Node.js Project:

Use npminit to initialize a Node.js project and create a package.json file:

npminit -y

Install the http Module:

The http module is a built-in module in Node.js, so you don't need to install it separately.

Create the Web Server Script:

Dept of CSE, GIET Engineering College, Rajahmundry


Webserver in Node.js

Create a JavaScript file (e.g., server.js) and write the code to create a simple web server:

const http = require('http');

// Create an HTTP server

const server = http.createServer((req, res) => {

res.writeHead(200, { 'Content-Type': 'text/plain' });

res.end('Hello, World!\n');

});

// Listen on port 3000

const port = 3000;

server.listen(port, () => {

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

});

In this script:

We import the http module.

We create an HTTP server using

http.createServer().

When a request is received, we set the HTTP response header to indicate a "200 OK" status and a
plain text content type. We then send the "Hello, World!" message as the response.

The server listens on port 3000, and a message is printed to the console when the server starts.

Start the Web Server:

Run the web server by executing the server.js script using Node.js:

Dept of CSE, GIET Engineering College, Rajahmundry


Webserver in Node.js

node server.js

Access the Web Server:

Open a web browser or use a tool like curl to access the web server. Open a web browser and
enter the following URL:

http://localhost:3000

You should see the "Hello, World!" message displayed in your browser.

Congratulations! You've created a simple web server in Node.js. You can extend this server by
handling different routes, serving HTML pages, and integrating with various Node.js packages
and frameworks for more complex web applications.

Program:

// Import the necessary modules

const http = require('http');

// Define the function to handle incoming requests

function handleRequest(request, response) {

// Set the response content type and status code

response.writeHead(200, {'Content-Type': 'text/plain'});

// Write a message to the response

response.write('Hello World!');

// End the response

response.end();

// Create a new server and set the request handler

Dept of CSE, GIET Engineering College, Rajahmundry


Webserver in Node.js

const server = http.createServer(handleRequest);

// Set the port number and start the server

const port = 3000;

server.listen(port, () => {

console.log(`Server running at http://localhost:${port}`);

});

node server.js

Sample input and Outputs:

Dept of CSE, GIET Engineering College, Rajahmundry


Webserver in Node.js

Result:
The code of Creating a Web Server in node.js is executed successfully without any errors.
References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)

Dept of CSE, GIET Engineering College, Rajahmundry


Modular Programming in Node.js

Modular programming in Node.js


Exp. No.:

Date:

Aim:

Module Name: Modular programming in Node.js.

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

Software Required:

HTML, Javascript, Node.js


Theory:

Modular programming is a fundamental practice in Node.js that involves breaking your


application's code into smaller, reusable modules. Node.js makes it easy to create, import, and use
modules, which helps keep your code organized, maintainable, and scalable. Here's a guide to
modular programming in Node.js:

Creating Modules:

In Node.js, a module is just a JavaScript file. To create a module:

Create a JavaScript File:

Start by creating a JavaScript file for your module. For example, let's create a module named
math.js:

// math.js

const add = (a, b) => a + b;

const subtract = (a, b) => a - b;

module.exports = {

add,

Dept of CSE, GIET Engineering College, Rajahmundry


Modular Programming in Node.js

subtract

};

In this example, we've defined two functions, add and subtract, and exported them as properties of
an object using module.exports.

Importing Modules:

Once you've created a module, you can import and use it in your Node.js application. To import a
module:

Use require():

In your application's JavaScript file, use the require() function to import the module. For example:

// app.js

const math = require('./math.js');

console.log(math.add(5, 3)); // Output: 8

console.log(math.subtract(10, 4)); // Output: 6

Here, we've imported the math.js module and used its functions.

Core Modules vs. Custom Modules:

Node.js has core modules (built-in modules) like http, fs (file system), and os. You can use these
modules without installing them separately. Custom modules are the ones you create, like the
math.js module in the example above.

CommonJS Module System:

Node.js follows the CommonJS module system, which includes the use of require() for importing
and module.exports for exporting modules. This system allows you to build a tree of modules that
form the structure of your application.

Dept of CSE, GIET Engineering College, Rajahmundry


Modular Programming in Node.js

Modularize Your Code:

To practice modular programming effectively:

Break your application into smaller, focused modules that each handle a specific task or
functionality.

Organize your modules into separate files and directories.

Reuse modules across different parts of your application to avoid code duplication.

Use clear and meaningful module names and file names to improve code readability.

By following these principles, you can build complex Node.js applications while keeping your
codebase clean and maintainable. Node.js's module system makes it easy to work with modules
and build scalable applications

Program:

Javascript

// Define a module to handle math operations

const mathModule = {

add: function(a, b) {

return a + b;

},

subtract: function(a, b) {

return a - b;

},

multiply: function(a, b) {

return a * b;

Dept of CSE, GIET Engineering College, Rajahmundry


Modular Programming in Node.js

},

divide: function(a, b) {

return a / b;

};

// Export the module for use in other files

module.exports = mathModule;

Javascript:

// Require the math module

const math = require('./math.js');

// Use the math module to perform some operations

const sum = math.add(5, 10);

console.log(`5 + 10 = ${sum}`);

const difference = math.subtract(15, 7);

console.log(`15 - 7 = ${difference}`);

const product = math.multiply(3, 4);

console.log(`3 * 4 = ${product}`);

const quotient = math.divide(20, 5);

console.log(`20 / 5 = ${quotient}`);

Dept of CSE, GIET Engineering College, Rajahmundry


Modular Programming in Node.js

Sample input and Outputs:

Result:
The code for Modular Programmingin node.js is executed successfully without any errors.
References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)

Dept of CSE, GIET Engineering College, Rajahmundry


Node Applications

Restarting Node Application


Exp. No.:

Date:

Aim:

Module Name: Restarting Node Application.

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

Software Required:

HTML, Javascript, Node.js


Theory:

To restart a Node.js application, you can follow these steps:

Identify the Process ID (PID):

You need to identify the process ID (PID) of the Node.js application you want to restart. There are
various ways to do this:

If you started the Node.js application from the command line, you might see the PID in the
terminal when you started it.

You can use the ps command on Unix-based systems to list running processes and filter for the

Node.js process:

ps aux | grep node

On Windows, you can use the Task Manager to find and terminate the Node.js process.

Terminate the Node.js Process:

Once you have identified the PID, you can terminate the Node.js process. You can use the kill
command on Unix-based systems or the Task Manager on Windows.

Dept of CSE, GIET Engineering College, Rajahmundry


Node Applications

On Unix-based systems (Linux, macOS), use the kill command with the PID:

kill -9 <PID>

Replace <PID> with the actual process ID of your Node.js application.

On Windows, open the Task Manager, find the Node.js process, and select "End Task" or "End
Process."

Restart the Application:

After terminating the existing Node.js process, you can restart the application as you normally
would, depending on how you initially started it:

If you started the application using the node command, you can run the command again to restart
it:

node your-app.js

If you're using a process manager like PM2 or Forever, you can use their commands to restart the
application:

For PM2:

pm2 restart your-app

For Forever:

forever restart your-app.js

Restarting the application will launch a new Node.js process with the updated code or
configuration.

Verify the Restart:

To ensure that the application has restarted successfully, you can check the logs or access the
application to verify its functionality.

Dept of CSE, GIET Engineering College, Rajahmundry


Node Applications

That's how you can restart a Node.js application. The exact steps may vary depending on your
operating system, how you initially started the application, and whether you're using any process
management tools.

Program:

npm install -g nodemon

const http = require('http');

const server = http.createServer((req, res) => {

res.write('Hello, World!');

res.end();

});

server.listen(3000, () => {

console.log('Server running on port 3000');

});

This will start the server and also start monitoring the app.js file for changes.

Sample input and Outputs:

Dept of CSE, GIET Engineering College, Rajahmundry


Node Applications

Result:
The code for Restarting Node Applicationsin node.js is executed successfully without any
errors.
References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)

Dept of CSE, GIET Engineering College, Rajahmundry


File Operations in Node.js

File OperationsIn Node.js


Exp. No.:

Date:

Aim:

Module Name: File Operations

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

Software Required:

HTML, Javascript, Node.js


Theory:

You can create a text file named src.txt and add the specified data to it using various methods,
including using a text editor or command-line tools. Here's how you can do it using command-line
tools on Unix-based systems (Linux or macOS):

Open a Terminal:

Open your terminal application. You can usually find it in your system's applications or use a
keyboard shortcut like Ctrl+Alt+T (Linux) or Command+Space and search for "Terminal"
(macOS).

Navigate to the Directory Where You Want to Create the File:

Use the cd (change directory) command to navigate to the directory where you want to create the
src.txt file. For example:

cd /path/to/your/directory

Replace /path/to/your/directory with the actual path to your desired directory.

Create and Edit the src.txt File:

You can use a text editor like nano, vim, or touch to create and edit the file. Here, we'll use nano
for simplicity:

Dept of CSE, GIET Engineering College, Rajahmundry


File Operations in Node.js

nano src.txt

This will open the src.txt file in the nano text editor.

Add the Data:

Type or paste the following data into the src.txt file:

Mongo, Express, Angular, Node.

Save and Exit:

To save the file in nano, press Ctrl + O, then press Enter. To exit, press Ctrl + X.

Verify the File:

You can verify that the file was created and contains the data by using the cat command:

cat src.txt

This will display the contents of the src.txt file in the terminal.

That's it! You've created a text file named src.txt and added the specified data to it using the
command line. You can also use graphical text editors to create and edit text files if you prefer a
more user-friendly interface.

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Middle Wares

Query Parameters
Exp. No.:

Date:

Aim:

Module Name: Defining a route, Handling Routes, Route Parameters, Query Parameters

Implement routing for the Adventure Trails application by embedding the necessary code in the
routes/route.js file.

Software Required:

HTML, Javascript, Express.js


Theory:

In web development, routes are a fundamental concept used to define how an application responds
to different URLs or endpoints. Routes help determine which code or function should be executed
when a specific URL is requested. Here's an overview of defining routes, handling routes, and
working with route parameters and query parameters:

Defining Routes:

To define routes in a web application, you typically need a web framework or router. Different
web frameworks have their own ways of defining routes, but the basic idea is the same. Here's a
simplified example using Express.js, a popular Node.js framework:

const express = require('express');

const app = express();

// Define a route for the homepage

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

res.send('Welcome to the homepage');

});

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Middle Wares

// Define a route for a contact page

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

res.send('Contact us at [email protected]');

});

// Start the server

app.listen(3000, () => {

console.log('Server is running on port 3000');

});

In this example, we've defined two routes, one for the homepage ("/") and one for the contact page
("/contact"). When a user accesses these URLs, the respective callback functions are executed.

Handling Routes:

Handling routes involves defining the logic that should execute when a specific route is accessed.
In the Express.js example above, we use the .get() method to define routes for handling HTTP
GET requests. Other frameworks may have different methods for handling different HTTP request
types (e.g., .post(), .put(), .delete()).

Route Parameters:

Route parameters allow you to capture dynamic values from the URL. For example, in a blog
application, you might have routes like "/blog/:id" where ":id" is a route parameter representing
the unique identifier of a blog post. You can access these parameters in your route handler using
the req.params object. Here's an example:

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

const blogId = req.params.id;

// Use blogId to fetch and display the specific blog post

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Middle Wares

res.send(`Displaying blog post with ID ${blogId}`);

});

When a user accesses "/blog/123", the blogId variable will be set to 123.

Query Parameters:

Query parameters are used to send additional data to the server as part of the URL. They are
typically preceded by a question mark ("?") and are in the format of "key=value". For example, in
the URL "/search?q=web+development", "q" is a query parameter with the value "web
development." You can access query parameters in your route handler using the req.query object.
Here's an example:

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

const query = req.query.q;

// Use the query parameter to perform a search

res.send(`Searching for: ${query}`);

});

When a user accesses "/search?q=web+development", the query variable will be set to "web
development."

Defining, handling, and working with route parameters and query parameters are essential skills in
web development when building dynamic and interactive web applications. The specific
implementation details may vary depending on the web framework or technology stack you're
using.

Program:

To implement routing for the Adventure Trails application, you'll typically need to use a web
framework like Express.js if you're working with Node.js. Below, I'll provide a basic example of
how you can set up routing in an Express.js application by embedding the necessary code in a
routes/route.js file.

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Middle Wares

Assuming you have a basic Express.js application set up, here's how you can create routes for
different pages in your Adventure Trails application:

First, make sure you have Express.js installed. If you haven't already installed it, you can do so
with:

npm install express

Create a routes directory in your project and a route.js file inside it. This file will contain your
route definitions.

- project_directory/

- routes/

- route.js

- app.js

In your route.js file, you can define routes and their respective handlers. Here's a simplified
example:

const express = require('express');

const router = express.Router();

// Define a route for the homepage

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

res.send('Welcome to Adventure Trails!');

});

// Define a route for the about page

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

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Middle Wares

res.send('Learn more about Adventure Trails.');

});

// Define a dynamic route for viewing a specific trail by its ID

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

const trailId = req.params.id;

// Fetch and display information about the trail with the specified ID

res.send(`Viewing Trail ${trailId}`);

});

module.exports = router;

In your main app.js file, import the route.js file and use it to set up routes:

const express = require('express');

const app = express();

const routes = require('./routes/route'); // Import the route.js file

// Use the route.js file to define routes

app.use('/', routes);

// Start the server

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {

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

});

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Middle Wares

With this setup, you have defined routes for the homepage, about page, and dynamic trail pages.
When users access different URLs like "/about" or "/trail/123", the appropriate route handlers in
route.js will be executed.

Sample input and Outputs:

Result:
The code for Route, Query Parametersin express.js is executed successfully without any errors.

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Middle Wares

Types of MiddleWares
Exp. No.:

Date:

Aim:

Module Name: How Middleware works, Chaining of Middlewares, Types of Middlewares

myNotes application: (i) we want to handle POST submissions. (ii) display customized error
messages. (iii) perform logging..

Software Required:

HTML, Javascript, Express.js


Theory:

To achieve the three requirements in your myNotes application – handling POST submissions,
displaying customized error messages, and performing logging – you'll need to make changes to
your server-side code. Below, I'll outline the steps and provide code snippets for each of these
requirements:

(i) Handling POST Submissions:

To handle POST submissions in your myNotes application, you need to use a web framework like
Express.js and define a route that handles incoming POST requests. Here's a basic example:

const express = require('express');

const app = express();

const bodyParser = require('body-parser'); // Middleware for parsing POST data

// Configure middleware to parse POST data

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

app.use(bodyParser.json());

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Middle Wares

// Define a route for handling POST submissions

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

const noteText = req.body.note; // Assuming the POST data contains a 'note' field

// Save the note to your database or perform other processing

res.send(`Received the following note: ${noteText}`);

});

// Start the server

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {

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

});

In this example, we're using the body-parser middleware to parse incoming POST data. When a
POST request is made to the "/submit" route, the data from the "note" field in the request body is
extracted and processed.

(ii) Displaying Customized Error Messages:

To display customized error messages in your myNotes application, you can use the res.status()
and res.send() methods to send error responses with appropriate status codes and messages. Here's
an example of handling errors and sending custom error messages:

// Define a route that might encounter an error

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

const noteId = req.params.noteId;

if (!noteId) {

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Middle Wares

res.status(400).send('Bad Request: Note ID is required');

} else {

// Fetch and display the note with the specified ID

// If the note is not found, you can send a 404 error

// If there's any other error, send a 500 error with an appropriate message

});

In this example, if the noteId parameter is missing or invalid, a 400 Bad Request error is sent with
a custom error message. You can similarly handle other error scenarios and send appropriate
status codes and messages.

(iii) Performing Logging:

To perform logging in your myNotes application, you can use the built-in console module in
Node.js. Here's how you can log messages for different events:

// Logging when the server starts

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

// Logging an error

console.error('An error occurred:', err);

// Logging information

console.info('Received a new note submission');

// Logging debug information (optional)

console.debug('Debugging information for a specific process');

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Middle Wares

You can use these logging statements strategically throughout your code to track the flow of your
application, capture errors, and gather information for debugging purposes.

Remember to configure your logging approach based on your specific needs, including choosing
where to log (e.g., console, file, external services) and what level of detail to log. You may also
consider using more advanced logging libraries like Winston or Morgan for more extensive
logging capabilities

Program:

const express = require('express');

const app = express();

const bodyParser = require('body-parser');

const fs = require('fs');

const morgan = require('morgan');

// Define a write stream for logging

const accessLogStream = fs.createWriteStream('./logs/access.log', { flags: 'a' });

// Use body-parser middleware to parse JSON

app.use(bodyParser.json());

// Use morgan middleware for logging

app.use(morgan('combined', { stream: accessLogStream }));

// POST endpoint for adding a note

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

const { title, content } = req.body;

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Middle Wares

// Check if title and content are present

if (!title || !content) {

return res.status(400).json({ error: 'Title and content are required' });

// Save the note to the database

// ...

// Return success response

return res.status(200).json({ message: 'Note added successfully' });

});

// Error handler middleware

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

console.error(err.stack);

return res.status(500).json({ error: 'Internal server error' });

});

// Start the server

app.listen(3000, () => {

console.log('Server started on port 3000');

});

Dept of CSE, GIET Engineering College, Rajahmundry


Types of Middle Wares

Sample input and Outputs:

Result:
The code for Middleware works in express.js is executed successfully without any errors.

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)

Dept of CSE, GIET Engineering College, Rajahmundry


MongoDB with Mongoose

MongoDB with Mongoose


Exp. No.:

Date:

Aim:

Module Name: Connecting to MongoDB with Mongoose, Validation Types and Defaults

Software Required:

HTML, Javascript, Express.js


Theory:

Connecting to MongoDB with Mongoose, defining validation types, and setting defaults is a
common task when working with Node.js and MongoDB. Mongoose is an Object Data Modeling
(ODM) library that simplifies interaction with MongoDB from Node.js. Below, I'll walk you
through the process of connecting to MongoDB, defining validation types, and setting defaults
using Mongoose.

Step 1: Install and Set Up Mongoose

Before you can work with MongoDB using Mongoose, make sure you have both Node.js and
MongoDB installed. Then, create a new Node.js project and install Mongoose:

npminit -y

npm install mongoose

Step 2: Connect to MongoDB

You need to establish a connection to your MongoDB database using Mongoose. Here's how you
can do it:

const mongoose = require('mongoose');

// Replace 'your_database_url' with your MongoDB connection string

const dbUrl = 'mongodb://your_username:your_password@your_host:your_port/your_database';

Dept of CSE, GIET Engineering College, Rajahmundry


MongoDB with Mongoose

mongoose.connect(dbUrl, { useNewUrlParser: true, useUnifiedTopology: true })

.then(() => {

console.log('Connected to MongoDB');

})

.catch((error) => {

console.error('Error connecting to MongoDB:', error);

});

Replace 'your_database_url' with the actual connection URL for your MongoDB database.

Step 3: Define a Mongoose Schema with Validation and Defaults

Now, you can define a Mongoose schema for your MongoDB collection. You can specify
validation rules and default values for the fields in your documents.

const mongoose = require('mongoose');

// Define a Mongoose schema

const userSchema = new mongoose.Schema({

username: {

type: String,

required: true, // Field is required

unique: true, // Field must be unique

trim: true, // Remove leading/trailing white spaces

},

email: {

Dept of CSE, GIET Engineering College, Rajahmundry


MongoDB with Mongoose

type: String,

required: true,

unique: true,

lowercase: true, // Convert to lowercase

validate: {

validator: (value) => {

// Use a custom validator function to check email format

return /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(value);

},

message: 'Invalid email format',

},

},

createdAt: {

type: Date,

default: Date.now, // Set a default value to the current date

},

});

// Create a Mongoose model based on the schema

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

module.exports = User;

Dept of CSE, GIET Engineering College, Rajahmundry


MongoDB with Mongoose

In this example, we defined a Mongoose schema for a User collection with fields like username,
email, and createdAt. We added validation rules such as required, unique, and a custom email
format validation. We also set a default value for the createdAt field to the current date.

Step 4: Using the Mongoose Model

Now that you have defined the schema, you can use the User model to interact with the MongoDB
collection. Here's an example of creating a new user and saving it to the database:

const User = require('./models/user'); // Import your Mongoose model

const newUser = new User({

username: 'john_doe',

email: '[email protected]',

});

newUser.save()

.then((user) => {

console.log('User saved:', user);

})

.catch((error) => {

console.error('Error saving user:', error);

});

This code creates a new User instance and saves it to the MongoDB database, applying the
validation and defaults defined in the schema.

By following these steps, you can connect to MongoDB using Mongoose, define validation rules
for your schema, and set default values for fields in your documents. This allows you to maintain
data integrity and consistency in your MongoDB database.

Dept of CSE, GIET Engineering College, Rajahmundry


MongoDB with Mongoose

Program:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

// Define the schema

const userSchema = new Schema({

name: {

type: String,

required: true,

trim: true

},

email: {

type: String,

required: true,

unique: true,

trim: true,

lowercase: true,

match: /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/

},

age: {

type: Number,

default: 18,

Dept of CSE, GIET Engineering College, Rajahmundry


MongoDB with Mongoose

min: 18,

max: 100

},

createdAt: {

type: Date,

default: Date.now

});

// Create the model

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

// Export the model

module.exports = User;

Sample input and Outputs:

Result:
The code for Connecting to Mongo DB with Mongoosein express.js is executed successfully
without any errors.

Dept of CSE, GIET Engineering College, Rajahmundry


MongoDB with Mongoose

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)

Dept of CSE, GIET Engineering College, Rajahmundry


Models

Models
Exp. No.:

Date:

Aim:

Module Name: Models

Write a program to wrap the Schema into a Model object.

Software Required:

HTML, Javascript, Express.js


Theory:

In JavaScript, the term "models" typically refers to objects or data structures that represent the
structure and behavior of entities or concepts within your application. Models are a fundamental
part of many programming paradigms, including object-oriented programming and data modeling.
They help organize and manage data, encapsulate business logic, and facilitate communication
between different parts of your application.

Here's an overview of what models are in JavaScript and how they are commonly used:

Object-Oriented Models:

In JavaScript, you can create models as JavaScript objects or classes. These models can represent
real-world entities or abstract concepts within your application. For example, if you are building a
web application for a library, you might have a Book model:

class Book {

constructor(title, author, ISBN) {

this.title = title;

this.author = author;

this.ISBN = ISBN;

Dept of CSE, GIET Engineering College, Rajahmundry


Models

displayInfo() {

console.log(`${this.title} by ${this.author}`);

const myBook = new Book('The Great Gatsby', 'F. Scott Fitzgerald', '978-0743273565');

myBook.displayInfo(); // Outputs: "The Great Gatsby by F. Scott Fitzgerald"

In this example, Book is a model class with properties (title, author, ISBN) and a method
(displayInfo) that defines the behavior of a book.

Data Models:

In many applications, models are used to represent and manage data retrieved from databases or
APIs. These data models often map directly to the structure of the data source. For example, if
you are building a user management system, you might have a User data model that matches the
schema of user records in your database:

const User = {

id: 1,

username: 'user123',

email: '[email protected]',

// ...

};

Data models are used to manipulate and interact with data from various sources, such as
databases, REST APIs, or JSON files.

MVC and Frameworks:

Dept of CSE, GIET Engineering College, Rajahmundry


Models

In web development, models are a core part of the Model-View-Controller (MVC) architectural
pattern. Frameworks like Angular, React, and Vue.js have their own implementations of models.
These models are used to manage the state of an application, often in a way that allows automatic
updating of views when the model changes.

For example, in React, you might use stateful components as models to manage the application's
data and state:

import React, { Component } from 'react';

class Counter extends Component {

constructor(props) {

super(props);

this.state = {

count: 0,

};

increment() {

this.setState({ count: this.state.count + 1 });

render() {

return (

<div>

<p>Count: {this.state.count}</p>

<button onClick={() =>this.increment()}>Increment</button>

Dept of CSE, GIET Engineering College, Rajahmundry


Models

</div>

);

export default Counter;

In this example, the Counter component acts as a model for managing the count state.

In summary, models in JavaScript can represent a wide range of concepts, from objects with
behavior to data structures for managing application data. Depending on your application's needs,
models play a crucial role in organizing and managing data and behavior, making your code more
maintainable and scalable.

Program:

Php

const mongoose = require('mongoose');

// Define the schema

const personSchema = new mongoose.Schema({

name: {

type: String,

required: true,

},

age: {

type: Number,

min: 0,

Dept of CSE, GIET Engineering College, Rajahmundry


Models

max: 120,

default: 18,

},

email: {

type: String,

required: true,

unique: true,

match: /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/,

},

});

// Create the model

const Person = mongoose.model('Person', personSchema);

// Export the model

module.exports = Person;

Sample input and Outputs:

Result:
The code for Models in express.js is executed successfully without any errors.

Dept of CSE, GIET Engineering College, Rajahmundry


Models

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)

Dept of CSE, GIET Engineering College, Rajahmundry


CRUD Operations

CRUD Operations

Exp. No.:

Date:

Aim:

Module Name: CRUD Operations

Write a program to perform various CRUD (Create-Read-Update-Delete) operations using


Mongoose library functions.

Software Required:

HTML, Javascript, Express.js


Theory:

CRUD operations (Create, Read, Update, Delete) are fundamental operations for managing data in
many software applications. In JavaScript, you can perform CRUD operations on data stored in
various forms, such as arrays, objects, databases, or external APIs. Here's an overview of how to
perform CRUD operations in JavaScript:

1. Create (C):

Creating new data or records is typically done using one of the following methods:

Adding to Arrays:

You can create new data by adding elements to arrays.

const myArray = [];

myArray.push('New item');

Creating Objects:

You can create new objects to represent data.

const myObject = {

Dept of CSE, GIET Engineering College, Rajahmundry


CRUD Operations

key1: 'value1',

key2: 'value2',

};

Storing Data in Databases/APIs:

When working with databases or external APIs, you often create new records by making POST
requests to create resources.

2. Read (R):

Reading data is about retrieving and displaying existing data. Here are common methods:

Reading from Arrays:

Access elements in an array by their index.

const myArray = ['Item 1', 'Item 2', 'Item 3'];

console.log(myArray[1]); // Outputs: "Item 2"

Accessing Object Properties:

Access properties of an object using dot notation or bracket notation.

const myObject = {

name: 'John',

age: 30,

};

console.log(myObject.name); // Outputs: "John"

Querying Databases/APIs:

Retrieve data from databases or APIs by making GET requests with appropriate queries or
parameters.

Dept of CSE, GIET Engineering College, Rajahmundry


CRUD Operations

3. Update (U):

Updating data involves modifying existing data. Here are some common methods:

Modifying Arrays:

You can change array elements by accessing them by index.

const myArray = ['Item 1', 'Item 2', 'Item 3'];

myArray[1] = 'Updated Item 2';

Modifying Object Properties:

You can update properties of an object.

const myObject = {

name: 'John',

age: 30,

};

myObject.age = 31;

Updating Databases/APIs:

To update records in databases or external APIs, you typically make PUT or PATCH requests to
modify existing resources.

4. Delete (D):

Deleting data involves removing existing data. Here are common methods:

Removing from Arrays:

Delete elements from an array, often using methods like splice() or pop().

const myArray = ['Item 1', 'Item 2', 'Item 3'];

Dept of CSE, GIET Engineering College, Rajahmundry


CRUD Operations

myArray.splice(1, 1); // Removes 'Item 2'

Deleting Object Properties:

You can delete properties from an object using the delete keyword.

const myObject = {

name: 'John',

age: 30,

};

delete myObject.age; // Removes the 'age' property

Deleting from Databases/APIs:

To delete records in databases or external APIs, you typically make DELETE requests to remove
existing resources.

CRUD operations in JavaScript can be performed on various data structures and storage systems,
depending on your application's requirements. When working with databases or external APIs,
you'll often use HTTP methods (GET, POST, PUT, DELETE) to interact with the data.
Additionally, libraries and frameworks like Express.js and Mongoose can simplify CRUD
operations when building web applications with Node.js and MongoDB.

Program:

Javascript

const mongoose = require('mongoose');

// Connect to the database

mongoose.connect('mongodb://localhost/mydatabase',

{ useNewUrlParser: true, useUnifiedTopology: true })

.then(() => console.log('Connected to the database'))

Dept of CSE, GIET Engineering College, Rajahmundry


CRUD Operations

.catch((error) =>console.error(error));

// Define the schema for our model

const studentSchema = new mongoose.Schema({

name: {

type: String,

required: true

},

age: Number,

grade: {

type: Number,

min: 0,

max: 100

});

// Create the model

const Student = mongoose.model('Student', studentSchema);

// Create a new student

const john = new Student({

name: 'John',

age: 18,

grade: 80

Dept of CSE, GIET Engineering College, Rajahmundry


CRUD Operations

});

// Save the student to the database

john.save()

.then(() => console.log('Student saved to the database'))

.catch((error) =>console.error(error));

// Find all students

Student.find()

.then((students) => console.log('All students:', students))

.catch((error) =>console.error(error));

// Find a student by ID

Student.findById('605aa10d7f80ba4e9c32dc25')

.then((student) => console.log('Student found by ID:', student))

.catch((error) =>console.error(error));

// Update a student by ID

Student.findByIdAndUpdate('605aa10d7f80ba4e9c32dc25', { age: 19 })

.then(() => console.log('Student updated successfully'))

.catch((error) =>console.error(error));

// Delete a student by ID

Student.findByIdAndDelete('605aa10d7f80ba4e9c32dc25')

.then(() => console.log('Student deleted successfully'))

.catch((error) =>console.error(error));

Dept of CSE, GIET Engineering College, Rajahmundry


CRUD Operations

Sample input and Outputs:

Result:
The code for CRUD Operationsin express.js is executed successfully without any errors.

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)

Dept of CSE, GIET Engineering College, Rajahmundry


API Development

API Development
Exp. No.:

Date:

Aim:

Module Name: API Development.

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.

Software Required:

HTML, Javascript, Express.js


Theory:

API development in JavaScript typically involves building RESTful APIs using server-side
technologies. In this response, I'll provide an overview of the steps involved in creating an
API using JavaScript, Node.js, and Express.js, which is a popular web application framework
for building APIs.

Step 1: Set Up Your Development Environment

Ensure you have Node.js and npm (Node Package Manager) installed on your system. You
can download and install them from the official Node.js website: https://nodejs.org/

Step 2: Create a New Node.js Project

Create a new directory for your project and navigate to it in your terminal.

Initialize a new Node.js project by running:

npminit

Follow the prompts to create a package.json file for your project.

Step 3: Install Express.js

Dept of CSE, GIET Engineering College, Rajahmundry


API Development

To create an API, you'll need a web framework like Express.js. Install it as a project
dependency:

npm install express

Step 4: Create Your API

Create an Express.js application in a JavaScript file (e.g., app.js):

const express = require('express');

const app = express();

const port = process.env.PORT || 3000; // Define the port to listen on

// Define a sample API route

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

res.json({ message: 'Hello, API!' });

});

// Start the server

app.listen(port, () => {

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

});

In this example, we've created a simple Express.js server with one API route ("/api/hello")
that returns a JSON response.

To run your API, execute:

node app.js

Step 5: Define API Endpoints and Routes

Dept of CSE, GIET Engineering College, Rajahmundry


API Development

Extend your API by defining more routes and endpoints to handle various HTTP methods
(GET, POST, PUT, DELETE). You can use Express.js's routing mechanism to do this:

// Example API route for retrieving a list of items

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

const items = ['Item 1', 'Item 2', 'Item 3'];

res.json({ items });

});

// Example API route for creating a new item

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

const newItem = req.body.item; // Assuming the client sends JSON data with an 'item'
property

// Save the new item to your database or data store

res.json({ message: 'Item created successfully', newItem });

});

// Define other API routes as needed for updating and deleting items

Step 6: Middleware and Data Processing

You can use middleware in Express.js to handle request parsing, authentication, logging, and
more. Middleware functions are executed before reaching the route handler. For example, to
parse JSON request bodies:

const bodyParser = require('body-parser');

// Parse JSON request bodies

app.use(bodyParser.json());

Dept of CSE, GIET Engineering College, Rajahmundry


API Development

Step 7: Error Handling

Implement error handling middleware to manage errors gracefully and provide meaningful
responses to clients:

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

console.error(err.stack);

res.status(500).json({ message: 'Something went wrong!' });

});

Step 8: Testing

Test your API endpoints thoroughly using tools like Postman, Insomnia, or writing automated
tests using testing libraries like Mocha and Chai.

Step 9: Deployment

Deploy your API to a production environment. Common choices include cloud platforms like
AWS, Heroku, or services like Vercel or Netlify.

Step 10: Documentation

Document your API using tools like Swagger, OpenAPI, or by creating API documentation
manually to make it easier for developers to understand and use your API.

API development in JavaScript is a vast topic, and the steps outlined above provide a basic
foundation for building a RESTful API using Node.js and Express.js. Depending on your
project's complexity and requirements, you may need to integrate with databases, handle
authentication, and implement more advanced features

Program:

const express = require('express');

const router = express.Router();

Dept of CSE, GIET Engineering College, Rajahmundry


API Development

const Note = require('../models/Note');

// Fetch note by ID

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

try {

const note = await Note.findById(req.params.id);

if (!note) {

return res.status(404).send('Note not found');

res.send(note);

} catch (error) {

res.status(500).send(error.message);

});

// Update note by ID

router.patch('/:id', async (req, res) => {

try {

const note = await Note.findByIdAndUpdate(req.params.id, req.body, { new: true });

if (!note) {

return res.status(404).send('Note not found');

res.send(note);

Dept of CSE, GIET Engineering College, Rajahmundry


API Development

} catch (error) {

res.status(500).send(error.message);

});

module.exports = router;

Sample input and Outputs:

Result:
The code for API Developmentin express.js is executed successfully without any errors.

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)

Dept of CSE, GIET Engineering College, Rajahmundry


Session Management, Cookies

Session Management, Cookies


Exp. No.:

Date:

Aim:

Module Name: Why Session management, Cookies

Software Required:

HTML, Javascript, Express.js


Theory:

Session management and cookies are essential concepts in web development, as they play a
crucial role in maintaining state and user authentication across HTTP, which is inherently
stateless. Let's explore why session management and cookies are important:

Session Management:

State Management: HTTP is a stateless protocol, meaning each HTTP request from a client to a
server is independent, and the server does not inherently remember previous requests. Session
management allows you to maintain state across multiple requests, making it possible to
remember user-specific data and actions.

User Authentication: Session management is crucial for user authentication. When a user logs in,
a session is typically created, and a unique session identifier (e.g., session ID) is assigned. This
session ID allows the server to recognize the user on subsequent requests, ensuring that they
remain authenticated without needing to re-enter credentials for every request.

Shopping Carts and E-commerce: In e-commerce websites, session management is used to store
the contents of a user's shopping cart. This enables users to add items to their cart, proceed to
checkout, and maintain their selected items throughout the shopping process.

User Tracking: Session management is also employed for tracking user behavior, such as the
pages they visit, actions they take, and preferences they set during a single session. This
information can be valuable for analytics and personalization.

Dept of CSE, GIET Engineering College, Rajahmundry


Session Management, Cookies

Cookies:

Persistent Data Storage: Cookies are small pieces of data stored on the client's browser. They are
used to persistently store information between different HTTP requests. Cookies can contain data
such as user preferences, language settings, or tracking information.

User Authentication: Cookies are commonly used for user authentication. When a user logs in, the
server sets a session cookie in the user's browser. This cookie is sent with each subsequent
request, allowing the server to identify the user and maintain their authenticated state.

Remember Me Functionality: Cookies are often used to implement "Remember Me" functionality
on login pages. When a user selects "Remember Me," a persistent cookie is set, allowing the user
to stay logged in even after closing and reopening the browser.

Tracking and Analytics: Cookies can be used for tracking user behavior and collecting analytics
data. For example, web analytics tools use cookies to track the number of unique visitors, page
views, and user interactions.

Customization: Cookies can be used to customize the user experience. Websites can remember
user preferences, such as theme choices, language settings, or font size, by storing this
information in cookies.

Targeted Advertising: In online advertising, cookies are often used to track user interests and
display targeted ads based on the user's browsing history and behavior.

While session management and cookies offer many benefits, it's important to be mindful of user
privacy and security. Implementing proper security measures, such as using secure cookies,
encrypting sensitive data, and handling user consent for tracking, is crucial to protect user
information and maintain trust. Additionally, adhering to regulations like GDPR and CCPA is
essential when handling user data through cookies and session management.

Dept of CSE, GIET Engineering College, Rajahmundry


Session Management, Cookies

Program:

Javascript
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());
// Set a cookie with a name and value
app.get('/set-cookie', (req, res) => {
res.cookie('myCookie', 'Hello World').send('Cookie set successfully');
});
// Read a cookie value
app.get('/read-cookie', (req, res) => {
const cookieValue = req.cookies.myCookie;
if (cookieValue) {
res.send(`Cookie value is: ${cookieValue}`);
} else {
res.send('Cookie not found');
}
});
// Clear a cookie
app.get('/clear-cookie', (req, res) => {
res.clearCookie('myCookie').send('Cookie cleared successfully');
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});

Dept of CSE, GIET Engineering College, Rajahmundry


Session Management, Cookies

Sample input and Outputs:

Result:
The code for Session management, Cookiesin express.js is executed successfully without any
errors.

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)

Dept of CSE, GIET Engineering College, Rajahmundry


Sessions

Sessions
Exp. No.:

Date:

Aim:

Module Name: Sessions

Write a program to explain session management using sessions.

Software Required:

HTML, Javascript, Express.js


Theory:

Session management and cookies are essential concepts in web development, as they play a
crucial role in maintaining state and user authentication across HTTP, which is inherently
stateless. Let's explore why session management and cookies are important:

Session Management:

State Management: HTTP is a stateless protocol, meaning each HTTP request from a client to
a server is independent, and the server does not inherently remember previous requests.
Session management allows you to maintain state across multiple requests, making it possible
to remember user-specific data and actions.

User Authentication:

Session management is crucial for user authentication. When a user logs in, a session is
typically created, and a unique session identifier (e.g., session ID) is assigned. This session ID
allows the server to recognize the user on subsequent requests, ensuring that they remain
authenticated without needing to re-enter credentials for every request.

Shopping Carts and E-commerce:

Dept of CSE, GIET Engineering College, Rajahmundry


Sessions

In e-commerce websites, session management is used to store the contents of a user's


shopping cart. This enables users to add items to their cart, proceed to checkout, and maintain
their selected items throughout the shopping process.

User Tracking:

Session management is also employed for tracking user behavior, such as the pages they visit,
actions they take, and preferences they set during a single session. This information can be
valuable for analytics and personalization.

Program:
Javascript
const express = require('express');
const session = require('express-session');
const app = express();
// Configure session middleware
app.use(session({
secret: 'mysecret', // Secret used to sign the session ID cookie
resave: false, // Don't save session if unmodified
saveUninitialized: false, // Don't create session until something is stored
cookie: { maxAge: 60000 } // Set session ID cookie expiration time (in ms)
}));
// Route to handle login requests
app.post('/login', (req, res) => {
// Perform authentication check
if (authenticated) {
// Set session variable
req.session.username = 'user123';
res.send('Login successful');
} else {
res.status(401).send('Authentication failed');

Dept of CSE, GIET Engineering College, Rajahmundry


Sessions

}
});
// Route to handle protected resource requests
app.get('/resource', (req, res) => {
// Check if user is authenticated
if (req.session.username) {
// User is authenticated, grant access to resource
res.send('Access granted');
} else {
// User is not authenticated, redirect to login page
res.redirect('/login');
}
});
// Start server
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
Sample input and Outputs:

Result:
The code for Sessionsin express.js is executed successfully without any errors.

Dept of CSE, GIET Engineering College, Rajahmundry


Sessions

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)

Dept of CSE, GIET Engineering College, Rajahmundry


Helmet MiddleWare

Security, Helmet Middleware


Exp. No.:

Date:

Aim:

Module Name: Why and What Security, Helmet Middleware.

Implement security features in myNotesapplication

Software Required:

HTML, Javascript, Express.js


Theory:

Security is a critical aspect of any application, and it is essential to ensure that user data and
application data are safe and secure from malicious attacks. In the myNotes application,
several security features can be implemented to ensure the security of the application.Some of
the security features that can be implemented in the myNotes application include:

Program:

1.Input validation: Ensure that all inputs are validated to prevent SQL injection and other
attacks.

2.Password encryption: Passwords should be encrypted using a secure hashing algorithm such
as bcrypt to prevent unauthorized access.

3.Cross-Site Scripting (XSS) protection: Implement measures to prevent XSS attacks by


sanitizing user inputs and using appropriate encoding techniques.

4.Cross-Site Request Forgery (CSRF) protection: Protect against CSRF attacks by using
tokens to verify that requests are coming from trusted sources.

5.Implement HTTPS: HTTPS provides a secure channel for communication between the
client and server, preventing man-in-the-middle attacks and data interception.

Dept of CSE, GIET Engineering College, Rajahmundry


Helmet MiddleWare

6.Helmet middleware: Helmet is a collection of middleware functions that implement various


security features such as setting HTTP headers to prevent attacks, enforcing HTTPS, and
protecting against XSS and CSRF attacks.

Sample input and Outputs:

Result:
The code for Helmet Middlewarein express.js is executed successfully without any errors.

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)

Dept of CSE, GIET Engineering College, Rajahmundry


Function

Basics of Typescript
Exp. No.:

Date:

Aim:

Module Name: Basics of typescript.

On the page, display 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

Software Required:

HTML, Javascript, Typescript


Theory:

TypeScript is a statically typed superset of JavaScript that adds optional static typing and
other features to help developers write more robust and maintainable code. Here are the basics
of TypeScript:

Installation:

To start using TypeScript, you first need to install it globally on your system (if not already
installed) and possibly locally in your project. You can do this using npm (Node Package
Manager):

npm install -g typescript

Creating a TypeScript File:

TypeScript files typically have a .ts extension. You can create a TypeScript file using a code
editor or IDE of your choice.

Dept of CSE, GIET Engineering College, Rajahmundry


Function

Basic Types:

TypeScript introduces static typing through the use of types. Here are some basic types in
TypeScript:

number: Represents numeric values, including integers and floating-point numbers.

string: Represents textual data.

boolean: Represents true or false values.

any: Represents a dynamic type that can hold any value.

void: Represents the absence of a value (often used for functions that don't return anything).

null and undefined: Represents null or undefined values.

Variable Declaration:

You can declare variables using let, const, or var as in JavaScript, but TypeScript allows you
to specify the variable's type:

let age: number = 30;

const name: string = "John";

Functions:

You can specify the types of function parameters and return values:

function add(x: number, y: number): number {

return x + y;

Interfaces:

Interfaces define the structure of objects and classes. They are used to enforce a specific shape
for objects:

Dept of CSE, GIET Engineering College, Rajahmundry


Function

interface Person {

name: string;

age: number;

const person: Person = { name: "Alice", age: 25 };

Classes:

TypeScript supports class-based object-oriented programming. You can define classes with
properties and methods:

class Animal {

constructor(public name: string) {}

makeSound() {

console.log("Some generic sound");

const cat = new Animal("Whiskers");

Type Annotations:

TypeScript allows you to explicitly annotate types or use type inference:

let num: number = 42; // Type annotation

let text = "Hello, TypeScript!"; // Type inference

Type Aliases and Union Types:

You can create custom type aliases and use union types to define more complex types:

Dept of CSE, GIET Engineering College, Rajahmundry


Function

type ID = string | number;

let userId: ID = "123";

Enums:

Enums allow you to define a set of named numeric constants:

enum Color {

Red,

Green,

Blue,

let favoriteColor: Color = Color.Blue;

Type Assertion:

Sometimes, you may need to tell the TypeScript compiler that you know more about the type
of a value than it does. You can use type assertions for this:

let value: any = "This is a string";

let length: number = (value as string).length;

Compiler:

To transpile TypeScript code into JavaScript, you can use the TypeScript compiler (tsc) from
the command line:

tscyourfile.ts

This generates a JavaScript file (yourfile.js) that you can execute in a browser or Node.js
environment.

Dept of CSE, GIET Engineering College, Rajahmundry


Function

These basics should give you a good starting point for working with TypeScript. As you
become more familiar with the language, you can explore more advanced features like
generics, decorators, and modules to write clean and maintainable code.

Program:

a.ts

const price: {[key: string]: string} = { GoldPlatinum: "$999", PinkGold: "$899", SilverTitanium:
"$949" };

console.log(`Price of Gold Platinum Mobile: ${price.GoldPlatinum}`);

console.log(`Price of Pink Gold Mobile: ${price.PinkGold}`);

console.log(`Price of Silver Titanium Mobile: ${price.SilverTitanium}`);

a.html

<!DOCTYPE html>

<html lang="en">

<body>

<script src="9a.js"></script>

</body>

</html>

Dept of CSE, GIET Engineering College, Rajahmundry


Function

Sample input and Outputs:

Result:
The code for Basics of typescriptis executed successfully without any errors.

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)

Dept of CSE, GIET Engineering College, Rajahmundry


Function

Function
Exp. No.:

Date:

Aim:

Module Name: Function.

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.

Software Required:

HTML, Javascript, Typescript


Theory:

Functions in TypeScript are similar to JavaScript functions, but TypeScript allows you to add type
annotations to function parameters and return values, making your code more predictable and
easier to understand. Here's an overview of functions in TypeScript:

Function Declaration:

You can declare a function in TypeScript like you would in JavaScript, but you can also specify
types for parameters and return values:

function add(x: number, y: number): number {

return x + y;

In this example, the add function takes two parameters, both of type number, and it returns a value
of type number.

Function Expression:

You can also define functions as expressions and assign them to variables:

Dept of CSE, GIET Engineering College, Rajahmundry


Function

const subtract = function(x: number, y: number): number {

return x - y;

};

Here, subtract is a variable that holds a function.

Arrow Functions:

TypeScript supports arrow functions, which provide a more concise syntax:

const multiply = (x: number, y: number): number => x * y;

Arrow functions automatically capture the surrounding this value.

Optional and Default Parameters:

You can specify optional parameters by adding a ? after the parameter name, and you can provide
default values for parameters:

function greet(name: string, age?: number, message: string = "Hello"): string {

return `${message}, ${name}${age ? ` (Age: ${age})` : ""}!`;

console.log(greet("Alice")); // Hello, Alice!

console.log(greet("Bob", 30)); // Hello, Bob (Age: 30)!

In this example, age is optional, and message has a default value of "Hello."

Rest Parameters:

TypeScript allows you to use the rest parameter syntax (...) to capture a variable number of
arguments into an array:

function sum(...numbers: number[]): number {

return numbers.reduce((total, num) => total + num, 0);

Dept of CSE, GIET Engineering College, Rajahmundry


Function

console.log(sum(1, 2, 3, 4, 5)); // 15

Function Overloads:

TypeScript supports function overloads, which allow you to provide multiple function signatures
for the same function:

function greet(name: string): string;

function greet(name: string, age: number): string;

function greet(name: string, age?: number): string {

if (age === undefined) {

return `Hello, ${name}!`;

} else {

return `Hello, ${name} (Age: ${age})!`;

console.log(greet("Alice")); // Hello, Alice!

console.log(greet("Bob", 30)); // Hello, Bob (Age: 30)!

This allows you to call the greet function with different argument combinations.

Higher-Order Functions:

TypeScript makes it easy to work with higher-order functions that accept functions as arguments
or return functions. For example, you can use map, filter, and reduce functions with type
annotations.

Dept of CSE, GIET Engineering College, Rajahmundry


Function

Generic Functions:

TypeScript supports generics, which allow you to write functions that work with different data
types while preserving type safety:

function identity<T>(arg: T): T {

return arg;

let result = identity<number>(42); // result is of type number

Program:

b.ts

// Define the product interface interface Product {

productId: number; name: string;

price: number;

// Define the product array const products: Product[] = [

{ productId: 1, name: "Product 1", price: 10 },

{ productId: 2, name: "Product 2", price: 20 },

{ productId: 3, name: "Product 3", price: 30 },

];

// Get the product list element

const productList: HTMLUListElement | null = document.querySelector("#product-list");

// Add event listener to the product list element if (productList) {

Dept of CSE, GIET Engineering College, Rajahmundry


Function

productList.addEventListener("click", handleProductSelection);

// Define the event handler function

function handleProductSelection(event: MouseEvent):

void {

const target: HTMLElement | null = event.target as HTMLElement;

if (target &&target.nodeName == "LI")

{const productId: number = parseInt(target.dataset.productId as string);

// Use arrow function to filter product array by productId const selectedProduct: Product |
undefined = products.find( (product) =>product.productId === productId

);

// Check if selected product exists

if (selectedProduct) {

// Pass selected product to next screen

// Example code for navigating to the next screen navigateToNextScreen(selectedProduct);

function navigateToNextScreen(selectedProduct: Product): void {

// Example code for navigating to the next screen

console.log(`Selected Product: ${selectedProduct.name} - Price: ${selectedProduct.price}`);

Dept of CSE, GIET Engineering College, Rajahmundry


Function

b.html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8" />

<title>Product Selection</title>

<script src="b.js" defer></script>

</head>

<body>

<h1>Select a Product</h1>

<ul id="product-list">

<li data-product-id="1">Product 1</li>

<li data-product-id="2">Product 2</li>

<li data-product-id="3">Product 3</li>

</ul>

</body>

</html>

Sample input and Outputs:

Dept of CSE, GIET Engineering College, Rajahmundry


Function

Result:
The code for Functiontypescript is executed successfully without any errors.

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)
8. https://infyspringboard.onwingspan.com/en/app/toc/lex_9436233116512678000_
shared/overview (Typescript)

Dept of CSE, GIET Engineering College, Rajahmundry


Parameter and Return Types

Parameter Types and Return Types


Exp. No.:

Date:

Aim:

Module Name: Parameter Types and Return Types.

Consider that developer needs to declare a function getMobileByVendor which accepts string as
input parameter and returns the list of mobiles

Software Required:

HTML, Javascript, Typescript


Theory:

In TypeScript, you can specify parameter types and return types for functions and methods using
type annotations. This helps you define the expected types of input parameters and the type of
value the function will return. TypeScript uses static type checking to ensure that your code
follows these type annotations correctly.

Here's how you can specify parameter types and return types in TypeScript:

Parameter Types:

You can specify parameter types by adding a colon (:) followed by the type after the parameter
name in a function or method signature. Here's an example:

function addNumbers(a: number, b: number): number {

return a + b;

In this example, a and b are parameters of type number, which means the function addNumbers
expects two numbers as input.

Dept of CSE, GIET Engineering College, Rajahmundry


Parameter and Return Types

Return Types:

You can specify the return type of a function or method using the colon (:) followed by the type
after the parameter list. Here's an example:

function addNumbers(a: number, b: number): number {

return a + b;

In this example, the addNumbers function returns a value of type number.

Void Return Type:

If a function doesn't return any value, you can specify its return type as void. For example:

function logMessage(message: string): void {

console.log(message);

In this example, the logMessage function logs a message to the console but doesn't return any
value.

Optional Parameters:

You can make a parameter optional by adding a question mark (?) after the parameter name, and
its type should be followed by a question mark. For example:

function greet(name: string, greeting?: string): string {

if (greeting) {

return `${greeting}, ${name}!`;

} else {

return `Hello, ${name}!`;

Dept of CSE, GIET Engineering College, Rajahmundry


Parameter and Return Types

In this example, the greeting parameter is optional, so you can call the greet function with or
without providing a greeting argument.

Default Parameter Values:

You can provide default values for parameters by assigning a value after the parameter's type. For
example:

function greet(name: string, greeting: string = "Hello"): string {

return `${greeting}, ${name}!`;

In this example, if you don't provide a greeting argument when calling the greet function, it will
default to "Hello."

By specifying parameter types and return types in TypeScript, you can catch type-related errors at
compile-time and write more robust and maintainable code.

Program:

c.ts

interface Mobile { name: string; vendor: string;

const mobiles: Mobile[] = [

{ name: 'iPhone 13', vendor: 'Apple' },

{ name: 'Galaxy S21', vendor: 'Samsung' },

{ name: 'OnePlus 9', vendor: 'OnePlus' },

Dept of CSE, GIET Engineering College, Rajahmundry


Parameter and Return Types

{ name: 'Pixel 6', vendor: 'Google' },

];

function getMobileByVendor(vendor: string):

Mobile[] { return mobiles.filter((mobile) =>mobile.vendor === vendor);

const appleMobiles = getMobileByVendor('Apple');

const googleMobiles =getMobileByVendor('Google');

const samsungMobiles = getMobileByVendor('Samsung');

console.log(appleMobiles); console.log(googleMobiles); console.log(samsungMobiles);

c.html

<!DOCTYPE html>

<html lang="en">

<body>

<script src="c.js"></script>

</body>

</html>

Dept of CSE, GIET Engineering College, Rajahmundry


Parameter and Return Types

Sample input and Outputs:

Result:
The code for Parameter and return types is executed successfully without any errors.

Dept of CSE, GIET Engineering College, Rajahmundry


Parameter and Return Types

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)
8. https://infyspringboard.onwingspan.com/en/app/toc/lex_9436233116512678000_
shared/overview (Typescript)

Dept of CSE, GIET Engineering College, Rajahmundry


Arrow Functions

Arrow Function
Exp. No.:

Date:

Aim:

Module Name: Arrow Function.

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 eq..

Software Required:

HTML, Javascript, Typescript


Theory:

In TypeScript, arrow functions are a concise way to define functions. They are similar to
regular JavaScript arrow functions but allow you to specify types for parameters and return
values, providing additional type safety.

Here's the basic syntax for an arrow function in TypeScript:

const add = (a: number, b: number): number => {

return a + b;

};

In this example:

add is the name of the function.

(a: number, b: number) specifies the parameters and their types.

: number specifies the return type of the function.

=> is the arrow notation indicating the beginning of the function body.

Dept of CSE, GIET Engineering College, Rajahmundry


Arrow Functions

You can also write shorter arrow functions without curly braces if they consist of a single
expression. In this case, TypeScript will infer the return type:

const add = (a: number, b: number): number => a + b;

Here are some key points to note about arrow functions in TypeScript:

Parameter Types: You can specify types for the function parameters, just like in regular
functions.

Return Type: You can specify the return type using the colon (:) notation.

Implicit Return: When the function body consists of a single expression, you can omit the
curly braces {} and the return keyword, as shown in the second example. TypeScript will
automatically infer the return type.

this Binding: Arrow functions capture the this value from their enclosing context. This is
different from regular functions, which have their own this binding. Arrow functions are often
used when you want to preserve the outer this context, such as in callbacks and event
handlers.

Here's an example of using an arrow function in a callback:

class Counter {

private count: number = 0;

constructor() {

document.addEventListener("click", () => {

// 'this' refers to the 'Counter' instance, not the event target.

this.count++;

console.log(`Clicked ${this.count} times.`);

});

Dept of CSE, GIET Engineering College, Rajahmundry


Arrow Functions

const counter = new Counter();

In this example, the arrow function passed to addEventListener captures the this value from
the Counter instance, allowing you to access the count property.

Arrow functions in TypeScript are a powerful and convenient way to define functions,
especially when working with modern JavaScript features and frameworks. They provide type
safety while maintaining a concise syntax.

Program:

9d.ts

interface Manufacturer { id: string;

price: number;

const manufacturers: Manufacturer[] = [

{ id: '1', price: 100 },

{ id: '2', price: 200 },

{ id: '3', price: 300 },

{ id: '4', price: 400 },

];

constmyfunction = (price: number):

void =>{ manufacturers.forEach((manufacturer) => { if (manufacturer.price>= price)

Dept of CSE, GIET Engineering College, Rajahmundry


Arrow Functions

console.log(`Manufacturer with ID ${manufacturer.id} has a price of


${manufacturer.price}`);

});

};

myfunction(250);

9d.html

<!DOCTYPE html>

<html lang="en">

<body>

<script src="9d.js"></script>

</body>

</html>

Dept of CSE, GIET Engineering College, Rajahmundry


Arrow Functions

Sample input and Outputs:

Result:
The code for Arrow Functionis executed successfully without any errors.

Dept of CSE, GIET Engineering College, Rajahmundry


Arrow Functions

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)
8. https://infyspringboard.onwingspan.com/en/app/toc/lex_9436233116512678000_
shared/overview (Typescript)

Dept of CSE, GIET Engineering College, Rajahmundry


Parameters

Optional and Default Parameters


Exp. No.:

Date:

Aim:

Module Name: Optional and Default Parameters.


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 should

Software Required:

HTML, Javascript, Typescript


Theory:

In TypeScript, you can use optional and default parameters to make your functions more
flexible and user-friendly. Optional parameters allow you to specify that certain function
parameters are not required when calling the function, while default parameters provide
default values for parameters that are omitted during the function call.

Optional Parameters:

To declare a parameter as optional, you simply add a question mark (?) at the end of the
parameter's name in the function signature. Here's an example:

function greet(name: string, greeting?: string): string {

if (greeting) {

return `${greeting}, ${name}!`;

} else {

return `Hello, ${name}!`;

Dept of CSE, GIET Engineering College, Rajahmundry


Parameters

console.log(greet("Alice")); // Output: Hello, Alice!

console.log(greet("Bob", "Hi")); // Output: Hi, Bob!

In the greet function, the greeting parameter is optional, so you can call the function with or
without providing a greeting argument.

Default Parameters:

To provide default values for parameters, you can assign a value to the parameter in the
function signature. Here's an example:

function greet(name: string, greeting: string = "Hello"): string {

return `${greeting}, ${name}!`;

console.log(greet("Alice")); // Output: Hello, Alice!

console.log(greet("Bob", "Hi")); // Output: Hi, Bob!

In this example, if you don't provide a greeting argument when calling the greet function, it
will default to "Hello."

Using Optional and Default Parameters Together:

You can also use optional and default parameters together in a function signature. When using
both, the optional parameter should come after the default parameter. Here's an example:

function greet(name: string, greeting: string = "Hello", punctuation?: string): string {

const message = `${greeting}, ${name}`;

return punctuation ? message + punctuation : message;

Dept of CSE, GIET Engineering College, Rajahmundry


Parameters

console.log(greet("Alice")); // Output: Hello, Alice

console.log(greet("Bob", "Hi")); // Output: Hi, Bob

console.log(greet("Charlie", undefined, "!")); // Output: Hello, Charlie!

In this example, name is a required parameter, greeting is a parameter with a default value,
and punctuation is an optional parameter. You can call the function with different
combinations of arguments based on your needs.

Optional and default parameters in TypeScript provide flexibility in how you define and use
functions, making your code more versatile and accommodating different usage scenarios.

Program:

9e.ts

interface Mobile { id: number; name: string;

manufacturer: string;

const mobiles: Mobile[] = [

{ id: 100, name: 'Galaxy S21', manufacturer: 'Samsung' },

{ id: 101, name: 'Galaxy S20', manufacturer: 'Samsung' },

{ id: 102, name: 'iPhone 13', manufacturer: 'Apple' },

{ id: 103, name: 'OnePlus 9', manufacturer: 'OnePlus' },

function getMobileByManufacturer(manufacturer: string, id?: number): Mobile[] {

let filteredMobiles = mobiles.filter((mobile) =>mobile.manufacturer === manufacturer); if


(id) {

Dept of CSE, GIET Engineering College, Rajahmundry


Parameters

filteredMobiles = filteredMobiles.filter((mobile) => mobile.id === id);

return filteredMobiles;

constsamsungMobiles = getMobileByManufacturer('Samsung');

console.log(samsungMobiles);

constsamsungMobile101 = getMobileByManufacturer

('Samsung', 101); console.log(samsungMobile101);

9e.html

<!DOCTYPE html>

<html lang="en">

<body>

<script src="9e.js"></script>

</body>

</html>

Dept of CSE, GIET Engineering College, Rajahmundry


Parameters

Sample input and Outputs:

Result:
The code for Optional and Default Parametersin typescriptis executed successfully without any
errors.
References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)
8. https://infyspringboard.onwingspan.com/en/app/toc/lex_9436233116512678000_
shared/overview (Typescript)

Dept of CSE, GIET Engineering College, Rajahmundry


Rest Parameters

Rest Parameter
Exp. No.:

Date:

Aim:

Module Name: Rest Parameter

Implement business logic for adding multiple Product values into a cart variable w is type
of string array.

Software Required:

HTML, Javascript, Typescript


Theory:

In TypeScript, a rest parameter allows you to capture an arbitrary number of arguments as an


array within a function. Rest parameters are denoted by an ellipsis (...) followed by the
parameter name in a function parameter list. They are particularly useful when you want to
work with a variable number of arguments in a function.

Here's the basic syntax for using rest parameters:

function sum(...numbers: number[]): number {

return numbers.reduce((total, num) => total + num, 0);

console.log(sum(1, 2, 3, 4, 5)); // Output: 15

In this example:

The ...numbers syntax indicates that the numbers parameter will capture any number of
arguments passed to the sum function.

Inside the function, numbers is an array containing all the arguments passed.

Dept of CSE, GIET Engineering College, Rajahmundry


Rest Parameters

You can also combine rest parameters with other parameters in a function:

function greet(greeting: string, ...names: string[]): string {

const nameList = names.join(", ");

return `${greeting}, ${nameList}!`;

console.log(greet("Hello", "Alice", "Bob", "Charlie")); // Output: Hello, Alice, Bob, Charlie!

In this example, the greet function takes a greeting parameter followed by a rest parameter
names, which captures multiple names passed as arguments.

Key points to remember about rest parameters in TypeScript:

Rest parameters must be the last parameter in a function's parameter list. You cannot have
other parameters after the rest parameter.

The rest parameter is an array that contains all the extra arguments passed to the function.

You can use rest parameters with any data type, not just numbers or strings.

Rest parameters are a powerful feature that allows you to work with variable-length argument
lists, making your functions more flexible and versatile when dealing with an unknown
number of inputs.

Program:

10a.ts

let cart: string[] = []; // Initialize an empty cart array

// Define a function to add products to the cart function addToCart(...products: string[]): void
{

cart.push(...products); // Use the spread operator to push multiple products to the cart

Dept of CSE, GIET Engineering College, Rajahmundry


Rest Parameters

// Example usage:

addToCart("Apple", "Grapes", "Mango"); // Add multiple products to the cart


console.log(cart);

10a.html

<!DOCTYPE html>

<html lang="en">

<body>

<script src="10a.js"></script>

</body>

</html>

Sample input and Outputs:

Dept of CSE, GIET Engineering College, Rajahmundry


Rest Parameters

Result:
The code for Rest Parameters is executed successfully without any errors.

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)
8. https://infyspringboard.onwingspan.com/en/app/toc/lex_9436233116512678000_
shared/overview (Typescript)

Dept of CSE, GIET Engineering College, Rajahmundry


Creating an Interface

Creating an Interface
Exp. No.:

Date:

Aim:

Module Name: Creating an Interface

Declare an interface named Product with two properties like productId and productName with
a number and string datatype and need to implement logic to populate the Product details.

Software Required:

HTML, Javascript, Typescript


Theory:

In TypeScript, you can create interfaces to define the structure of objects, classes, and
function types. Interfaces are a way to specify a contract for objects to adhere to, ensuring that
they have specific properties and methods. Here's how you can create an interface in
TypeScript:

// Define an interface for a simple object

interface Person {

firstName: string;

lastName: string;

age: number;

// Create an object that adheres to the Person interface

const person: Person = {

firstName: "John",

Dept of CSE, GIET Engineering College, Rajahmundry


Creating an Interface

lastName: "Doe",

age: 30,

};

console.log(person.firstName); // Output: John

console.log(person.lastName); // Output: Doe

console.log(person.age); // Output: 30

In this example:

We define an interface named Person using the interface keyword.

The Person interface specifies that any object implementing it must have properties firstName
(a string), lastName (a string), and age (a number).

We create an object person that adheres to the Person interface by having the required
properties.

You can also use interfaces with classes to define the shape of a class. For example:

interface Animal {

name: string;

makeSound(): void;

class Dog implements Animal {

constructor(public name: string) {}

makeSound() {

console.log(`${this.name} barks.`);

Dept of CSE, GIET Engineering College, Rajahmundry


Creating an Interface

const myDog = new Dog("Buddy");

myDog.makeSound(); // Output: Buddy barks.

In this case:

We define an interface Animal that specifies that any class implementing it must have a name
property (string) and a makeSound method (a function with no arguments and no return
value).

The Dog class implements the Animal interface by providing the required properties and
methods.

Interfaces can also be used to define function types. For example:

interface MathOperation {

(a: number, b: number): number;

const add: MathOperation = (a, b) => a + b;

const subtract: MathOperation = (a, b) => a - b;

console.log(add(5, 3)); // Output: 8

console.log(subtract(10, 4)); // Output: 6

In this example, we define an interface MathOperation for a function that takes two numbers
as arguments and returns a number. We then create two functions (add and subtract) that
adhere to this interface.

Interfaces in TypeScript provide a way to define contracts and enforce type safety, making
your code more reliable and maintainable. They are particularly useful when working with
complex data structures or ensuring that classes and functions conform to expected shapes.

Dept of CSE, GIET Engineering College, Rajahmundry


Creating an Interface

Program:

10b.ts

// Declare the Product interface interface Product {

productId: number; productName: string;

// Define a function to create a new Product object

function createProduct(productId: number, productName: string): Product {

// Create a new Product object using the specified values const product: Product = {
productId, productName }; return product;

// Example usage:

const newProduct: Product = createProduct(8459, "Mobile Phone"); // Create a new Product


object console.log(newProduct);

10b.html

<!DOCTYPE html>

<html lang="en">

<body>

<script src="10b.js"></script>

</body>

</html>

Dept of CSE, GIET Engineering College, Rajahmundry


Creating an Interface

Sample input and Outputs:

Result:
The code for Creating an Interface in typescript is executed successfully without any errors.

Dept of CSE, GIET Engineering College, Rajahmundry


Creating an Interface

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)
8. https://infyspringboard.onwingspan.com/en/app/toc/lex_9436233116512678000_
shared/overview (Typescript)

Dept of CSE, GIET Engineering College, Rajahmundry


Duck Typing

Duck Typing
Exp. No.:

Date:

Aim:

Module Name: Duck Typing

Declare an interface named Product with two properties like productld and productName with
the number and string datatype and need to implement logic to populate the Product details.

Theory:

Duck typing is a concept in TypeScript (and in dynamically typed languages like JavaScript)
that focuses on an object's behavior (methods and properties) rather than its explicit type. In
other words, if an object walks like a duck and quacks like a duck, it's treated as a duck,
regardless of its actual class or type. This approach allows for more flexible and dynamic
code.

In TypeScript, duck typing is closely related to the concept of structural typing. Two types are
considered compatible (i.e., they "match") if their structures are compatible, meaning they
have the same shape or structure. If two objects have the same properties with compatible
types, TypeScript will consider them to have the same type, even if they weren't explicitly
defined as such.

Here's an example illustrating duck typing in TypeScript:

interface Bird {

fly(): void;

interface Fish {

swim(): void;

Dept of CSE, GIET Engineering College, Rajahmundry


Duck Typing

function move(animal: Bird | Fish) {

if ("fly" in animal) {

animal.fly();

} else if ("swim" in animal) {

animal.swim();

} else {

console.log("This animal can't fly or swim.");

const bird: Bird = {

fly() {

console.log("The bird is flying.");

},

};

const fish: Fish = {

swim() {

console.log("The fish is swimming.");

},

};

move(bird); // Output: The bird is flying.

Dept of CSE, GIET Engineering College, Rajahmundry


Duck Typing

move(fish); // Output: The fish is swimming.

In this example:

We have two interfaces, Bird and Fish, representing different animals with their respective
methods.

The move function accepts a parameter that can be either a Bird or a Fish.

Inside the move function, we check whether the input object has the fly or swim methods
using the in operator to determine the behavior of the object.

The move function can accept both bird and fish objects because they have the required
methods, even though their types were not explicitly declared as Bird or Fish.

Duck typing is particularly useful in scenarios where you want to write more flexible and
reusable code by focusing on the capabilities of objects rather than their specific types. It
allows for more dynamic and adaptable code that can work with a wider range of objects as
long as they satisfy the expected behavior.

Program:

10c.ts

interface Product { productId: number; productName: string;

const product: Product = { productId: 8459, productName: "Mobile"

};

console.log(product);

10c.html

<!DOCTYPE html>

<html lang="en">

Dept of CSE, GIET Engineering College, Rajahmundry


Duck Typing

<body>

<script src="10c.js"></script>

</body>

</html>

Sample input and Outputs:

Dept of CSE, GIET Engineering College, Rajahmundry


Duck Typing

Result:
The code for Duck Typingin typescript is executed successfully without any errors.
References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)
8. https://infyspringboard.onwingspan.com/en/app/toc/lex_9436233116512678000_
shared/overview (Typescript)

Dept of CSE, GIET Engineering College, Rajahmundry


Function Types

Function Types
Exp. No.:

Date:

Aim:

Module NameFunction Types

Declare an interface with function type and access its value.

Software Required:

HTML, Javascript, Typescript


Theory:

In TypeScript, you can define function types to specify the expected shape or signature of a
function. Function types describe the parameters a function should take and the type of value
it should return. This is useful when you want to define callbacks, function parameters, or
method signatures.

Here's how you can define and use function types in TypeScript:

Function Type Syntax:

To define a function type, you use a combination of parameter names and types followed by
an arrow (=>) and the return type. For example:

// Define a function type

type AddFunction = (a: number, b: number) =>number;

// Create a function that adheres to the AddFunction type

const add: AddFunction = (a, b) => a + b;

console.log(add(5, 3)); // Output: 8

program:

Dept of CSE, GIET Engineering College, Rajahmundry


Function Types

10d.ts

interface Calculator {

(x: number, y: number): number;

const add: Calculator = (x, y) =>{ return x + y;

};

console.log(add(54, 31));

10d.html

<!DOCTYPE html>

<html lang="en">

<body>

<script src="10d.js"></script>

</body>

</html>

Sample input and Outputs:

Dept of CSE, GIET Engineering College, Rajahmundry


Function Types

Result:
The code for Function Typesin typescript is executed successfully without any errors.
References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)
8. https://infyspringboard.onwingspan.com/en/app/toc/lex_9436233116512678000_
shared/overview (Typescript)

Dept of CSE, GIET Engineering College, Rajahmundry


Extending Intefaces

Extending Interfaces
Exp. No.:

Date:

Aim:

Module Name: Extending Interfaces

Declare a product List interface which extends properties from two other declared interfaces
like Category.Product as well as implementation to create a variable of this interface type.

Software Required:

HTML, Javascript, Typescript


Theory:

In TypeScript, you can extend interfaces to create new interfaces that inherit properties and
methods from one or more existing interfaces. This allows you to build upon existing
interfaces, promote code reusability, and ensure that derived interfaces include the members
of the base interfaces. Here's how you can extend interfaces in TypeScript:

Basic Interface Extension:

You can extend an interface using the extends keyword. Here's an example:

interface Shape {

color: string;

interface Circle extends Shape {

radius: number;

const myCircle: Circle = {

Dept of CSE, GIET Engineering College, Rajahmundry


Extending Intefaces

color: "red",

radius: 5,

};

console.log(myCircle.color); // Output: red

console.log(myCircle.radius); // Output: 5

program:

11a.ts
interface Category {

id: number;

name: string;

interface Product {

id: number;

name: string;

price: number;

interface productList extends Category, Product {

description: string;

const myProduct: productList = {

id: 1,

Dept of CSE, GIET Engineering College, Rajahmundry


Extending Intefaces

name: "My Product",

price: 10.99,

description: "This is my product",

};

console.log(myProduct);

11a.html
<!DOCTYPE html>

<html lang="en">

<body>

<script src="11a.js"></script>

</body>

</html>

Sample input and Outputs:

Dept of CSE, GIET Engineering College, Rajahmundry


Extending Intefaces

Result:
The code of Function for Typesof Extending interface in typescript is executed successfully
without any errors.
References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)
8. https://infyspringboard.onwingspan.com/en/app/toc/lex_9436233116512678000_
shared/overview (Typescript)

Dept of CSE, GIET Engineering College, Rajahmundry


Classes

Classes
Exp. No.:

Date:

Aim:

Module Name: Classes

Consider the Mobile Cart applwhich extends properties from two other declared interfaces
like Category.Productlist array.

Software Required:

HTML, Javascript, Typescript


Theory:

In TypeScript, you can define classes to create object-oriented structures in your code. Classes
are a fundamental building block for organizing and encapsulating your code. They allow you
to define both the structure (properties) and behavior (methods) of objects.

Here's a basic example of how to create and use classes in TypeScript:

class Person {

// Properties

firstName: string;

lastName: string;

// Constructor

constructor(firstName: string, lastName: string) {

this.firstName = firstName;

this.lastName = lastName;

Dept of CSE, GIET Engineering College, Rajahmundry


Classes

// Method

sayHello() {

console.log(`Hello, my name is ${this.firstName} ${this.lastName}.`);

// Creating an instance of the Person class

const person1 = new Person("John", "Doe");

person1.sayHello(); // Output: Hello, my name is John Doe.

In this example:

We define a class named Person with properties firstName and lastName, a constructor that
initializes these properties, and a method sayHello that logs a greeting.

We create an instance of the Person class using the new keyword and call the sayHello
method on the instance.

Key features of classes in TypeScript:

Properties: You can define properties (fields) to hold data within the class.

Constructor: The constructor is a special method that gets called when you create an instance
of the class. It is used to initialize class properties.

Methods: You can define methods within the class to encapsulate behavior.

Access Modifiers: TypeScript supports access modifiers like public, private, and protected to
control the visibility and accessibility of class members.

Inheritance: You can create subclass (derived) classes that inherit properties and methods
from a base (parent) class.

class Student extends Person {

Dept of CSE, GIET Engineering College, Rajahmundry


Classes

studentId: number;

constructor(firstName: string, lastName: string, studentId: number) {

super(firstName, lastName); // Call the base class constructor

this.studentId = studentId;

study() {

console.log(`${this.firstName} is studying.`);

const student1 = new Student("Alice", "Smith", 12345);

student1.sayHello(); // Output: Hello, my name is Alice Smith.

student1.study(); // Output: Alice is studying.

Getters and Setters: TypeScript allows you to define getter and setter methods for class
properties to control access and modification.

class Circle {

private _radius: number;

constructor(radius: number) {

this._radius = radius;

get radius(): number {

return this._radius;

Dept of CSE, GIET Engineering College, Rajahmundry


Classes

set radius(value: number) {

if (value >= 0) {

this._radius = value;

} else {

console.error("Invalid radius. Radius must be non-negative.");

const circle = new Circle(5);

console.log(circle.radius); // Output: 5

circle.radius = -1; // Output: Invalid radius. Radius must be non-negative.

Classes in TypeScript provide a structured and object-oriented way to organize and manage
your code, making it more maintainable and easier to work with, especially for larger projects.

Program:

11b.ts

class Product {

constructor(public id: number, public name: string, public price: number) {}

const product1 = new Product(1, "iPhone 13", 999.99);

const product2 = new Product(2, "Samsung Galaxy S21", 899.99);

Dept of CSE, GIET Engineering College, Rajahmundry


Classes

const product3 = new Product(3, "Google Pixel 6", 799.99);

const productList: Product[] = [product1, product2, product3];

productList.forEach(product => {

console.log(product.name);

});

11b.html
<!DOCTYPE html>
<html lang="en">
<body>
<script src="11b.js"></script>
</body>
</html>
Sample input and Outputs:

Dept of CSE, GIET Engineering College, Rajahmundry


Classes

Result:
The code for Classes in typescript is executed successfully without any errors.
References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)
8. https://infyspringboard.onwingspan.com/en/app/toc/lex_9436233116512678000_
shared/overview (Typescript)

Dept of CSE, GIET Engineering College, Rajahmundry


Constructor

Constructor
Exp. No.:

Date:

Aim:

Module Name: Constructor

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 value>>"

Software Required:

HTML, Javascript, Typescript


Theory:

In TypeScript, a constructor is a special method in a class that gets called when you create an
instance (object) of that class. The constructor is used to initialize the object's properties and
perform any necessary setup when an instance is created. Here's how you define and use
constructors in TypeScript:

class Person {

firstName: string;

lastName: string;

// Constructor

constructor(firstName: string, lastName: string) {

this.firstName = firstName;

this.lastName = lastName;

Dept of CSE, GIET Engineering College, Rajahmundry


Constructor

// Creating an instance of the Person class

const person1 = new Person("John", "Doe");

console.log(person1.firstName); // Output: John

console.log(person1.lastName); // Output: Doe

program:
11c.ts
class Product {
private productId: number;
constructor(id: number) {
this.productId = id;
}
getProductId(): string {
return `Product id is ${this.productId}`;
} }
const product = new Product(58647);
console.log(product.getProductId()); // Output: Product id is 123
11c.html
<!DOCTYPE html>
<html lang="en">
<body>
<script src="11c.js"></script>
</body>
</html>

Dept of CSE, GIET Engineering College, Rajahmundry


Constructor

Sample input and Outputs:

Result:
The code for Constructor in typescript is executed successfully without any errors.
References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)
8. https://infyspringboard.onwingspan.com/en/app/toc/lex_9436233116512678000_
shared/overview (Typescript)

Dept of CSE, GIET Engineering College, Rajahmundry


Access Modifier

Access Modifiers
Exp. No.:

Date:

Aim:

Module Name: Access Modifiers


Create a Product class with 4 properties namely productId, productName, product Price,
productCategory with private, public, static, and protected access modifiers and accessing
them through Gadget class and its methods.

Software Required:

HTML, Javascript, Typescript


Theory:

Access modifiers in TypeScript are keywords that control the visibility and accessibility of
class members (properties and methods). They determine which parts of a class are accessible
from outside the class and which are not. TypeScript provides three main access modifiers:
public, private, and protected.

public: Members marked as public are accessible from anywhere, both within the class and
from external code.

private: Members marked as private are only accessible within the class in which they are
defined. They cannot be accessed from outside the class.

protected: Members marked as protected are accessible within the class and its subclasses
(derived classes), but not from external code.

Program:

11d.ts

class Product {

private productId: number;

Dept of CSE, GIET Engineering College, Rajahmundry


Access Modifier

public productName: string;

protected productPrice: number;

public productCategory: string;

constructor(id: number, name: string, price: number, category: string) {

this.productId = id;

this.productName = name;

this.productPrice = price;

this.productCategory = category;

public getProductId(): string {

return `Product id is ${this.productId}`;

public getPrice(): number {

return this.productPrice;

class Gadget extends Product {

public displayProduct(): void {

console.log(`Product name: ${this.productName}`);

console.log(`Product price: ${this.getPrice()}`);

console.log(`Product category: ${this.productCategory}`);

Dept of CSE, GIET Engineering College, Rajahmundry


Access Modifier

const mobile = new Gadget(101, 'Mobile', 10000, 'Electronics');

mobile.displayProduct(); // Output: Product name: Mobile, Product price: 10000, Product


category: Electronics

11d.html

<!DOCTYPE html>

<html lang="en">

<body>

<script src="11d.js"></script>

</body>

</html>

Sample input and Outputs:

Result:
The code for Access Modifiersin typescript is executed successfully without any errors.

Dept of CSE, GIET Engineering College, Rajahmundry


Access Modifier

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)
8. https://infyspringboard.onwingspan.com/en/app/toc/lex_9436233116512678000_
shared/overview (Typescript)

Dept of CSE, GIET Engineering College, Rajahmundry


Properties and Methods

Properties and Methods

Exp. No.:

Date:

Aim:

Module Name: Properties and Methods


Create a Product class with 4 properties namely productId and methods to setProductId)
and getProductId().
Software Required:

HTML, Javascript, Typescript


Theory:

In JavaScript, properties and methods are fundamental concepts used to define and work with
objects. Objects in JavaScript can have properties, which are essentially variables that belong
to the object, and methods, which are functions that are associated with the object. Here's an
overview of properties and methods in JavaScript:

Properties:

Properties are variables that belong to an object. They represent the characteristics or
attributes of the object. Properties can be of any data type, including numbers, strings,
booleans, objects, or even functions. You can access and modify object properties using dot
notation (object.property) or bracket notation (object["property"]).

Here's an example of defining and accessing object properties:

const person = {

firstName: "John",

lastName: "Doe",

age: 30,

isStudent: false,

Dept of CSE, GIET Engineering College, Rajahmundry


Properties and Methods

};

console.log(person.firstName); // Accessing property using dot notation

console.log(person["lastName"]); // Accessing property using bracket notation

person.age = 31; // Modifying a property

person.city = "New York"; // Adding a new property

console.log(person.age); // Output: 31

console.log(person.city); // Output: New York

Methods:

Methods are functions that are associated with objects. They represent the behaviors or
actions that objects can perform. Methods are defined as properties of an object, where the
property value is a function. You can call methods on objects using dot notation
(object.method()).

Here's an example of defining and calling object methods:

const calculator = {

add: function (a, b) {

return a + b;

},

subtract: function (a, b) {

return a - b;

},

};

const result1 = calculator.add(5, 3); // Calling the add method

Dept of CSE, GIET Engineering College, Rajahmundry


Properties and Methods

const result2 = calculator.subtract(10, 4); // Calling the subtract method

console.log(result1); // Output: 8

console.log(result2); // Output: 6

In modern JavaScript, you can use shorthand notation when defining methods within objects:

const calculator = {

add(a, b) {

return a + b;

},

subtract(a, b) {

return a - b;

},

};

This shorthand syntax is equivalent to the previous example.

Properties and methods are essential for working with objects in JavaScript. They allow you
to encapsulate data and behavior within objects, making your code more organized and
modular. You can also access and manipulate object properties and call methods to perform
specific tasks or operations.

Program:

12a.ts

class Product {

private _productId: number;

constructor(productId: number) { this._productId = productId;

Dept of CSE, GIET Engineering College, Rajahmundry


Properties and Methods

get productId(): number { return this._productId;

set productId(productId: number) { this._productId = productId;

constmyProduct = new Product(123);

console.log(myProduct.productId);

myProduct.productId = 456;

console.log(myProduct.productId);

12a.html

<!DOCTYPE html>

<html lang="en">

<body>

<script src="12a.js"></script>

</body>

</html>

Dept of CSE, GIET Engineering College, Rajahmundry


Properties and Methods

Sample input and Outputs:

Result:
The code for Properties and Method in typescript is executed successfully without any errors.
References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000

Dept of CSE, GIET Engineering College, Rajahmundry


Properties and Methods

_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)
8. https://infyspringboard.onwingspan.com/en/app/toc/lex_9436233116512678000_
shared/overview (Typescript)

Dept of CSE, GIET Engineering College, Rajahmundry


Namespaces

Creating and using Namespaces


Exp. No.:

Date:

Aim:

Module Name: Creating and using Namespaces


Create namespace called ProductUtility and place the Product class definition in it. Import the
Product class inside productlist file and use it.

Software Required:

HTML, Javascript, Typescript


Theory:

In TypeScript, namespaces (previously called internal modules) are a way to organize and
encapsulate code into separate named scopes. Namespaces are used to prevent naming
conflicts and improve code organization. You can think of namespaces as containers for
related code, similar to how modules work in many other programming languages.

Here's how you can create and use namespaces in TypeScript:

Creating a Namespace:

To create a namespace, you use the namespace keyword followed by the namespace name.
Inside the namespace, you can declare variables, functions, classes, or other namespaces.

namespace MyNamespace {

export const variable1 = 10;

export function sayHello(name: string) {

console.log(`Hello, ${name}!`);

Dept of CSE, GIET Engineering College, Rajahmundry


Namespaces

In this example, we define a namespace called MyNamespace, which contains a variable


variable1 and a function sayHello.

Using Items from a Namespace:

You can access items (variables, functions, classes, etc.) from a namespace by using the
namespace name followed by a dot (.) and the item's name.

console.log(MyNamespace.variable1); // Output: 10

MyNamespace.sayHello("Alice"); // Output: Hello, Alice!

Exporting Items from a Namespace:

By default, items declared inside a namespace are not accessible from outside the namespace.
To make items accessible from outside the namespace, you can use the export keyword.

namespace MyNamespace {

export const variable1 = 10;

export function sayHello(name: string) {

console.log(`Hello, ${name}!`);

With the export keyword, variable1 and sayHello can be accessed from outside the
MyNamespace namespace, as shown in the previous example.

Nesting Namespaces:

You can also nest namespaces within other namespaces to create a hierarchical structure.

namespace OuterNamespace {

export namespace InnerNamespace {

Dept of CSE, GIET Engineering College, Rajahmundry


Namespaces

export constnestedVariable = "Nested Value";

console.log(OuterNamespace.InnerNamespace.nestedVariable); // Output: Nested Value

Using Aliases for Namespaces:

You can use import statements to create aliases for namespaces to make them easier to work
with.

import ns = MyNamespace;

console.log(ns.variable1); // Output: 10

ns.sayHello("Bob"); // Output: Hello, Bob!

Namespaces are a way to structure and organize your TypeScript code, especially when you
are working on larger projects with many components or libraries. However, it's worth noting
that with the introduction of ECMAScript modules (ES modules) in TypeScript, they are
often preferred for organizing code due to their standardization and better compatibility with
modern JavaScript development practices. Still, namespaces can be useful in certain
scenarios, particularly when working with older code or legacy systems.

Program:

ProductUtility.ts

namespace ProductUtility{ export class Product { private productId: number;

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

public getProductId(): number { return this.productId;

Dept of CSE, GIET Engineering College, Rajahmundry


Namespaces

// Export the Product class as a global variable (window as any).Product = Product;

productlist.ts

// Import the Product class as a global variable declare const Product: any;

const product = new ProductUtility.Product();

product.setProductId(56); console.log(product.getProductId());

12b.html

<!DOCTYPE html>

<html>

<head>

<title>Product List</title>

<script src="ProductUtility.js"></script>

<script src="productlist.js"></script>

</head>

<body>

<h1>Product List</h1>

<p>Product ID: <span id="productId"></span></p>

<script>

const product2 = new ProductUtility.Product(); product2.setProductId(120);

document.getElementById('productId').textContent = product2.getProductId().toString();

Dept of CSE, GIET Engineering College, Rajahmundry


Namespaces

</script>

</body>

</html>

Sample input and Outputs:

Result:
The code for Creating and using Namespacein typescript is executed successfully without any errors.

Dept of CSE, GIET Engineering College, Rajahmundry


Namespaces

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)
8. https://infyspringboard.onwingspan.com/en/app/toc/lex_9436233116512678000_
shared/overview (Typescript)

Dept of CSE, GIET Engineering College, Rajahmundry


Modules

Creating and using Modules


Exp. No.:

Date:

Aim:

Module Name: Creating and using Modules


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.

Software Required:

HTML, Javascript, Typescript


Theory:

In TypeScript, modules are a way to organize and encapsulate code into separate files.
Modules help in managing the structure and dependencies of your code by allowing you to
break your code into smaller, reusable pieces. TypeScript supports two main types of
modules: internal (or ambient) modules and external modules (also known as ES modules).

Here's how you can create and use both types of modules in TypeScript:

Internal (Ambient) Modules (Deprecated):

Internal modules are the original way to structure code in TypeScript, but they are now
considered deprecated in favor of external modules (ES modules) and namespaces. Still, you
might encounter them in older TypeScript codebases.

Defining an Internal Module:

You can define an internal module by using the module keyword.

module MyModule {

export const variable1 = 10;

Dept of CSE, GIET Engineering College, Rajahmundry


Modules

export function sayHello(name: string) {

console.log(`Hello, ${name}!`);

Using Items from an Internal Module:

You can access items from an internal module by using the module name followed by a dot (.)
and the item's name.

console.log(MyModule.variable1); // Output: 10

MyModule.sayHello("Alice"); // Output: Hello, Alice!

External Modules (ES Modules):

External modules, also known as ES modules, are the modern way to organize code in
TypeScript. They follow the ECMAScript standard for modules and are widely supported in
modern browsers and Node.js.

Defining an External Module:

To define an external module, create a separate TypeScript file (e.g., myModule.ts) that
contains your module's code.

// myModule.ts

export const variable1 = 10;

export function sayHello(name: string) {

console.log(`Hello, ${name}!`);

Using Items from an External Module:

Dept of CSE, GIET Engineering College, Rajahmundry


Modules

You can import items from an external module using the import statement.

import { variable1, sayHello }

from "./myModule";

console.log(variable1); // Output: 10

sayHello("Bob"); // Output: Hello, Bob!

External modules are the preferred way to structure code in TypeScript because they are more
standardized and have better support for modern JavaScript development practices.

Default Exports:

In addition to named exports, you can also use default exports in external modules to export a
single default value or function. Here's how you can use default exports:

// myModule.ts

constdefaultVariable = "Default Value";

export default defaultVariable;

// Importing a default export

import myDefault from "./myModule";

console.log(myDefault); // Output: Default Value

Modules in TypeScript provide a way to manage code organization and dependencies, making
your codebase more modular, maintainable, and reusable. It's recommended to use external
modules (ES modules) for new TypeScript projects, as they align with modern JavaScript
practices.

Program:

mobile-cart.ts

namespace Mobile_Cart {

Dept of CSE, GIET Engineering College, Rajahmundry


Modules

export function calculateTotalPrice(quantity: number, price: number): number { return


quantity * price;

12c.html

<!DOCTYPE html>

<html>

<head>

<title>Mobile Cart</title>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

</head>

<body>

<h1>Mobile Cart</h1>

<form>

<label for="quantity">Quantity:</label>

<input type="number" id="quantity" name="quantity"><br>

<label for="price">Price:</label>

<input type="number" id="price" name="price"><br>

<button type="button" onclick="calculateTotalPrice()">Calculate Total Price</button>

</form>

Dept of CSE, GIET Engineering College, Rajahmundry


Modules

<div>

<label for="totalPrice">Total Price:</label>

<input type="number" id="totalPrice" readonly>

</div>

<script src="mobile-cart.js"></script>

<script>

function calculateTotalPrice() {

constquantityInput = document.getElementById("quantity");

constpriceInput = document.getElementById("price");

consttotalPriceInput = document.getElementById("totalPrice");

const quantity = Number(quantityInput.value); const price = Number(priceInput.value);

if (isNaN(quantity) || isNaN(price)) { alert("Please enter a valid quantity and price."); return;

consttotalPrice = Mobile_Cart.calculateTotalPrice(quantity, price);

totalPriceInput.value = totalPrice.toFixed(2);

</script>

</body>

</html>

Dept of CSE, GIET Engineering College, Rajahmundry


Modules

Sample input and Outputs:

Result:
The code for Creating and using Modulesin typescript is executed successfully without any errors.

Dept of CSE, GIET Engineering College, Rajahmundry


Modules

References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)
8. https://infyspringboard.onwingspan.com/en/app/toc/lex_9436233116512678000_
shared/overview (Typescript)

Dept of CSE, GIET Engineering College, Rajahmundry


Generic Array and functions

Generic Array and function to sort numbers


Exp. No.:

Date:

Aim:

Module Name: What is Generics, What are Type Parameters, Generic Functions, Generic
Constraints
Create a generic array and function to sort numbers as well as string values

Software Required:

HTML, Javascript, Typescript


Theory:

Generics in TypeScript provide a way to create reusable and flexible code components that
work with different data types. They allow you to write functions, classes, or interfaces that
can work with a variety of data types while maintaining type safety. Generics are particularly
useful when you want to write functions or data structures that are independent of the specific
data type they operate on.

Here are some key concepts related to generics in TypeScript:

1. Type Parameters (Generics):

Type parameters, also known as generics, are placeholders for data types that you can use to
create flexible and reusable code. You define these placeholders by enclosing a type variable
within angle brackets (< and >). By convention, type parameters are named with single
uppercase letters, such as T, U, or E.

function identity<T>(value: T): T {

return value;

constnumberValue = identity(42); // The type parameter T is inferred as number

Dept of CSE, GIET Engineering College, Rajahmundry


Generic Array and functions

conststringValue = identity("Hello"); // The type parameter T is inferred as string

In this example, T is a type parameter that represents an arbitrary data type. The identity
function uses the type parameter to accept and return a value of the same type. TypeScript
infers the type of T based on the argument provided when calling the function.

2. Generic Functions:

Generic functions are functions that use type parameters to work with different data types.
They allow you to write functions that are flexible and type-safe across a range of data types.

function swap<T, U>(a: T, b: U): [T, U] {

return [b, a];

const swapped = swap(42, "Hello"); // swapped: [string, number]

In this example, the swap function uses two type parameters, T and U, to swap the values of
two different data types. The return type of the function is a tuple containing the swapped
values with their respective types.

3. Generic Constraints:

Generic constraints allow you to restrict the types that can be used with a type parameter. You
can specify that a type parameter must extend a particular type, implement an interface, or
meet specific criteria.

interface Lengthwise {

length: number;

function getLength<T extends Lengthwise>(obj: T): number {

return obj.length;

Dept of CSE, GIET Engineering College, Rajahmundry


Generic Array and functions

conststrLength = getLength("Hello"); // strLength: number

constarrLength = getLength([1, 2, 3]); // arrLength: number

In this example, the getLength function uses a generic constraint to ensure that the type
parameter T must be an object that has a length property of type number. This constraint
makes it safe to access the length property within the function.

Generics are a powerful feature in TypeScript that allows you to write highly reusable and
type-safe code, especially when dealing with functions, classes, and data structures that need
to work with multiple data types. They enhance the flexibility and maintainability of your
code by providing a way to create versatile components without sacrificing type safety.

Program:

12d.ts

// Generic array

let arr: Array<number | string> = [3, 1, "b", 2, "a"];

// Generic function to sort numbers as well as string values

function sortArray<T extends number | string>(arr: Array<T>): Array<T> { return arr.sort();

// Sort the array

let sortedArr = sortArray(arr); console.log(sortedArr);

12d.html

<!DOCTYPE html>

<html>

<head>

Dept of CSE, GIET Engineering College, Rajahmundry


Generic Array and functions

<title>Generic Array Sort</title>

<script src="12d.js"></script>

</head><body><script>

// Use the sorted array

let arr1 = [4, 9, "e", 2, "g"];

let sortedArr1 = sortArray(arr1); console.log(sortedArr1);

</script>

</body>

</html>

Dept of CSE, GIET Engineering College, Rajahmundry


Generic Array and functions

Sample input and Outputs:

Result:
The code for Generic functions, typesin typescript is executed successfully without any errors.
References:

1. Pro Mean Stack Development,1stEdition, ELadElrom, ApressO’Reilly.


2. Full Stack JavaScript Development with MEAN, ColinJIhrig, AdamBretz,
1stedition, SitePoint, SitePointPty.Ltd, O'ReillyMedia.
3. Web Technologies, HTML, JavaScript, PHP, Java, JSP, XML and AJAX,
Black book, 1stEdition, DreamTech.
4. An Introduction to Web Design, Programming, 1stEdition, PaulSWang,
SandaSKatila, Cengage Learning.
5. https://infyspringboard.onwingspan.com/en/app/toc/lex_17739732834840810000
_shared/overview(HTML5)
6. https://infyspringboard.onwingspan.com/en/app/toc/lex_18109698366332810000
_shared/overview(Javascript)
7. https://infyspringboard.onwingspan.com/en/app/toc/lex_32407835671946760000
_shared/overview(Node.js&Express.js)
8. https://infyspringboard.onwingspan.com/en/app/toc/lex_9436233116512678000_
shared/overview (Typescript)

Dept of CSE, GIET Engineering College, Rajahmundry

You might also like