Lab Manual Full
Lab Manual Full
EXPERIMENT 1A)
AIM:
Types of Elements: HTML has several types of elements, including structural elements (such as
<html>, <head>, and <body>), text-level elements (such as <p> and <span>), and multimedia
elements (such as <img>, <audio>, and <video>).
HTML Elements - Attributes: HTML elements can be customized with attributes, which provide
additional information about the element and how it should be displayed or used. Examples of
attributes include "class" for defining CSS styles, "id" for identifying a specific element, and
"href" for specifying a hyperlink.
Metadata Element: The metadata element (<meta>) is used to provide information about the
HTML document that is not displayed in the browser window. This includes information such
as the author, description, and keywords, which can be used by search engines to index and
display the webpage in search results.
PROGRAM:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>IEKart's Shopping</title>
</head>
<body>
</body>
</html>
OUTPUT:
1.b )
AIM:
Enhance the Homepage.html of IEKart's Shopping Application by adding
appropriate sectioning elements.
DESCRIPTION:
Sectioning elements in HTML are used to divide the content of a web page into logical sections,
making it easier for users to understand and navigate the content. These elements include
<header>, <nav>, <section>, <article>, <aside>, and <footer>. The <header> element is used to
identify the header section of a page, while the <nav> element is used to define a set of
navigation links.
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<header>
</header>
<nav>
</nav>
<main>
<section>
<h1>Featured Products</h1>
</section>
<section>
<h1>Categories</h1>
</section>
<section>
</section>
</main>
<aside>
</aside>
<footer>
</footer>
</body>
</html>
OUTPUT:
1.c )
AIM: Make use of appropriate grouping elements such as list items to "About Us" page of
IEKart's Shopping Application
Division and Span Elements: The <div> and <span> elements are used to group elements and
apply styles or classes to them. The <div> element is a block-level element, while the <span>
element is an inline-level element.
List Element: The <ul>, <ol>, and <li> elements are used to create lists in HTML. The <ul>
element creates an unordered list, the <ol> element creates an ordered list, and the <li> element
defines each item in the list.
PROGRAM:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>About Us</h1>
<p>We are IEKart's, an online shopping website that sells goods in retail.</p>
<h2>Our Team</h2>
<ul>
</ul>
<h2>Our Mission</h2>
<ul>
<li>To continuously innovate and improve our offerings to meet the changing needs of our
customers.</li>
</ul>
</body>
</html>
OUTPUT:
1.d )
AIM:
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.
DESCRIPTION:
The Link element (<link>) is an HTML element used to define a relationship between the
current document and an external resource. This element is commonly used to link stylesheets
to an HTML document, allowing the page to be styled with CSS.
PROGRAM:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<ul>
<li><a href="Homepage.html">Home</a></li>
<li><a href="Products.html">Products</a></li>
<li><a href="Login.html">Login</a></li>
</ul>
<h1>About Us</h1>
<p>...</p>
<h2>Categories</h2>
<ul>
<li><a href="#electronics">Electronics</a></li>
<li><a href="#clothing">Clothing</a></li>
<li><a href="#accessories">Accessories</a></li>
</ul>
<h2 id="electronics">Electronics</h2>
<p>...</p>
<h2 id="clothing">Clothing</h2>
<p>...</p>
<h2 id="accessories">Accessories</h2>
<p>...</p>
<footer>
</footer>
</body>
</html>
OUTPUT:
1.e )
AIM: Add the © symbol in the Home page footer of IEKart's Shopping application.
DESCRIPTION:
In HTML, character entities are special codes used to represent special characters that are not
part of the standard character set. These entities are defined by their unique entity name or a
numeric code and are used to display symbols, foreign characters, mathematical symbols, and
more. Examples of character entities include < for <, > for >, and & for &.
PROGRAM:
<footer>
</footer>
OUTPUT:
1.F)
AIM:
Add the global attributes such as contenteditable, spellcheck, id etc. to enhance the
Signup Page functionality of IEKart's Shopping application.
DESCRIPTION:HTML5 Global Attributes are attributes that can be used on any HTML
element and are not limited to specific elements. These attributes can be used to provide
additional information about an element, such as defining the class or id, setting styles, and
assigning event handlers. Some commonly used global attributes include "class", "id", "style",
"title", and "data-*".
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>Signup</h1>
<label for="username">Username:</label>
contenteditable="true"><br><BR>
<label for="email">Email:</label>
<br><BR>
<label for="password">Password:</label>
<br><BR>
required><br><BR>
</form>
</body>
</html>
OUTPUT:
EXPERIMENT-2A)
DESCRIPTION:Table elements in HTML are used to display data in a tabular format and can
be customized using attributes such as colspan/rowspan, border, cellspacing, and cellpadding.
PROGRAM:
<!DOCTYPE html>
<head><title>Product Details</title></head>
<body>
<div class="product-details">
<h1>Product Name</h1>
<tr>
<th>Model</th>
<th>Color</th>
<th>Storage</th>
<th>Price</th>
<th>Availability</th>
</tr>
<tr>
<td>Model A</td>
<td>Black</td>
<td>64GB</td>
<td>$699</td>
<td>In stock</td>
</tr>
<tr>
<td>Model A</td>
<td>White</td>
<td>128GB</td>
<td>$799</td>
<td>In stock</td>
</tr>
<tr>
<td>Model B</td>
<td>Black</td>
<td>64GB</td>
<td>$799</td>
<td>Out of stock</td>
</tr>
<tr>
<td>Model B</td>
<td>White</td>
<td>128GB</td>
<td>$899</td>
<td>In stock</td>
</tr></table></div></body></html>
OUTPUT
2.b)
AIM: Using the form elements create Signup page for IEKart's Shopping application.
DESCRIPTION:Form elements in HTML are used to collect user input and can be customized
with various attributes such as input type, name, placeholder, and required. The color and date
pickers allow users to choose colors and dates from a graphical interface, while select and
datalist elements provide a dropdown menu for users to select from a pre-defined list of options
PROGRAM:
<!DOCTYPE html>
<head>
</head>
<body>
<h1>Signup</h1>
<label for="name">Name:</label>
<label for="email">Email:</label>
<label for="password">Password:</label>
</form>
</body>
</html>
OUTPUT:
2.c )
AIM:Enhance Signup page functionality of IEKart's Shopping application by adding
attributes to input elements
DESCRIPTION: elements in HTML are used to collect user input and can be customized using
various attributes such as type, name, value, placeholder, autofocus, required, disabled, and
readonly. These attributes provide additional functionality and control over how users can
interact with the input element. For example, the type attribute can specify whether the input
should be a text box, checkbox, radio button, or other types of input. The required attribute can
indicate that the user must provide input in order to submit the form, while the readonly attribute
can indicate that the user cannot modify the input value
PROGRAM:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Signup</h1>
<label for="name">Name:</label>
<label for="email">Email:</label>
<label for="password">Password:</label>
title="Password must contain at least one lowercase letter, one uppercase letter, one
number, and be at least 8 characters long"><br>
<label for="address">Address:</label>
</form>
</body>
</html>
OUTPUT
2.D)
AIM: Add media content in a frame using audio, video, iframe elements to the Home
pageofIEKart's Shopping application.
DESCRIPTION:Media elements are used to embed multimedia content such as audio and
video into a webpageIframe elements are used to embed external content such as web
pages or maps directly into a webpage, and can be customized with attributes like "src"
and "scrolling."
PROGRAM:
<!DOCTYPE html>
<head>
<title>IEKart's Shopping Application</title>
</head>
<body>
<h1>Welcome to IEKart's Shopping
Application</h1>
<h2>Featured Products</h2>
<p>Check out our latest products:</p>
<ul>
<li>Product 1</li>
<li>Product 2</li>
<li>Product 3</li>
</ul>
<h2>Product Video</h2>
<video width="400" height="300" controls>
<source src="product_video.mp4"
type="video/mp4"> Your browser does not
support the video tag.
</video>
<h2>Product Audio</h2>
<audio controls>
<source src="product_audio.mp3"
type="audio/mpeg"> Your browser does not
support the audio element.
</audio>
<h2>Related Article</h2>
<iframe width="400" height="300" src="https://www.example.com/article"
frameborder="0"></iframe></body></html>
OUTPUT
EXPERIMENT 3.a )
AIM:
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)
DESCRIPTION:
In JavaScript, there are three types of identifiers: variables, functions, and labels. Variable
identifiers are used to name variables, function identifiers are used to name functions, and label
identifiers are used to label statements. Identifiers must follow certain naming conventions, such
as starting with a letter or underscore, and can contain letters, numbers, and underscores.
PROGRAM:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="result"></p>
document.getElementById("radius").value; let
document.getElementById("result").innerHTML =
</script>
</body>
</html>
OUTPUT:
3.b )
AIM:
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.
DESCRIPTION:
Primitive data types are the building blocks of data and include undefined, null, boolean,
number, and string. They are called "primitive" because they are immutable and have a fixed
size in memory.
Non-primitive data types include objects and arrays, and are also known as reference types.
These data types can be of any size and can be changed dynamically. They are called
"reference" types because they are not stored directly
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<title>Movie Details</title>
</head>
<body>
<h1>Movie Details</h1>
<div id="movieDetails"></div>
<script>
const ratings = {
IMDB: 9.3,
RottenTomatoes: 91,
Metacritic: 80,
};
constmovieDetailsDiv = document.getElementById("movieDetails");
movieDetailsDiv.innerHTML = `
<h2>${movieName}</h2>
<p>Language: ${language}</p>
<p>Ratings:</p>
<ul>
<li>IMDB: ${ratings.IMDB}</li>
<li>Metacritic: ${ratings.Metacritic}</li>
</ul>
`;
</script>
</body>
</html>
OUTPUT:
3.c )
AIM:
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.
DESCRIPTION:
Operators are symbols used in JavaScript to perform operations on values or variables. There
are different types of operators in JavaScript such as arithmetic operators, assignment operators,
comparison operators, logical operators, bitwise operators, and more
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<form>
readonly><br><br></form>
document.getElementById("num_tickets").value; constpricePerTicket =
document.getElementById("price_per_ticket").value; consttotalPrice =
document.getElementById("total_price").value = totalPrice;
document.getElementById("discounted_amount").value =
discountedAmount;
</script>
</body>
</html>
OUTPUT:
3.d )
AIM:
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.
DESCRIPTION:
In JavaScript, there are two main types of statements: non-conditional statements and
conditional statements. Non-conditional statements are executed in a sequential order, whereas
conditional statements allow us to execute code based on a certain condition. The two main
types of conditional statements are "if" statements and "switch" statements. "If" statements are
used to execute a block of code if a specified condition is true, while "switch" statements are
used to perform different actions based on different conditions
PROGRAM:
<!DOCTYPE html>
<html>
<head>
let numTickets =
parseInt(document.getElementById("numTickets").value);
} else {
</script>
</head>
<body>
<div id="totalCost"></div>
</body>
</html>
OUTPUT:
3.e )
AIM:
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
DESCRIPTION:
In JavaScript, loops are used to execute a set of statements repeatedly until a certain condition
is met. There are three types of loops in JavaScript: for loop: This loop executes a block of
while loop: This loop executes a block of code as long as the condition is TRUE
do-while loop: This loop executes a block of code once before checking the condition. If the
condition is true, the loop will repeat
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p id="price"></p>
if (numSeats<= 2) { totalPrice =
numSeats * pricePerTicket;
return;
} else {
if (i<= 2) {
totalPrice += pricePerTicket;
} else {
totalPrice += pricePerTicket;
</script>
</body>
</html>
OUTPUT:
4.a )
AIM:
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.
DESCRIPTION:
Functions are reusable blocks of code that perform a specific task. In JavaScript, there are
several types of functions, including:
Named Functions: These functions are defined using the function keyword, followed by the
function name, and a pair of parentheses. They can be invoked by calling their name.
Anonymous Functions: These functions are defined without a name, and are often used as
callbacks or event listeners.
Arrow Functions: Introduced in ES6, arrow functions are a shorthand way of writing anonymous
functions.
Function Parameters: Functions can accept one or more parameters, which act as inputs to the
function.
Nested Functions: Functions can be defined inside other functions, creating a hierarchy of
functions.
Built-in Functions: JavaScript comes with several built-in functions, such as parseInt(),
parseFloat(), and Math.random().
Variable Scope in Functions: Variables declared inside a function have local scope, and are not
accessible outside of the function. Variables declared outside of a function have global scope,
and can be accessed anywhere in the code.
To declare a function in JavaScript, use the function keyword, followed by the function name,
and a pair of parentheses. The code inside the function is enclosed in curly braces. To invoke the
function, simply call its name, optionally passing in any required parameters.
PROGRAM:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
} else {
document.getElementById("totalPrice").value = totalPrice;
</script>
</body>
</html>
OUTPUT:
4.b )
AIM:
Create an Employee class extending from a base class Person. Hints: (i) Create a class
Person with name and age as attributes. (ii) Add a constructor to initialize the values
(iii) Create a class Employee extending Person with additional attributes role
DESCRIPTION:
Working with classes in JavaScript involves creating and using objects that have a defined set of
properties and behaviors. Classes are used to define the structure and behavior of objects, and
can be created and instantiated using the class keyword.
Classes in JavaScript can also inherit properties and methods from other classes, which is
known as inheritance. Inheritance allows classes to reuse code and build on existing
functionality, which can lead to more efficient and organized code.
To create a class, the class keyword is used, followed by the name of the class and a set of curly
braces. Properties and methods are defined within the class using constructor functions and
prototype methods.
To inherit from a class, the extends keyword is used to specify the class being inherited from.
Inherited properties and methods can be accessed using the super keyword
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<title>Employee Information</title>
</head>
<body>
<h2>Employee Information</h2>
<div id="employee"></div>
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
super(name, age);
this.role = role;
Age: ${emp.age}<br>
Role: ${emp.role}`;
</script></body></html>
OUTPUT:
4.c )
AIM:
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
DESCRIPTION:
In-built events are predefined actions or occurrences that can be triggered by user actions or
system events such as clicks, mouse movements, keypresses, and form submissions. Handlers
are functions that are executed in response to events.
JavaScript provides several in-built event handlers such as onclick, onmouseover, onkeydown,
onchange, and many more that can be used to perform actions on web pages when certain events
occur. These event handlers can be used to make web pages more interactive and userfriendly by
providing dynamic behavior to web elements
PROGRAM:
<!DOCTYPE html>
<html>
<head>
numOfSeats = document.getElementById("seats").value;
time!");
} else {
</script>
</head>
<body>
<p id="totalPrice"></p>
</body>
</html>
OUTPUT:
4.d )
AIM:
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,
DESCRIPTION:
Objects are one of the fundamental concepts in JavaScript, and they are used to store and
manipulate data. There are several types of objects in JavaScript, including built-in objects,
custom objects, and host objects.
Types of Objects:
Built-in Objects: These are the objects that are built into the JavaScript language, such as Array,
Date, Math, and RegExp.
Custom Objects: These are the objects that you create in your JavaScript code.
Host Objects: These are the objects that are provided by the browser or environment in which
your JavaScript code is running, such as window, document, and XMLHttpRequest
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<style> body {
background-color: #f2f2f2;
} h1 {
font-size: 36px;
text-align: center;
color: #333;
.cone { margin:
background-color: white;
position: relative;
overflow: hidden;
.empty:after {
content: "";
width: 160px;
height: 160px;
background-color:
white; position:
absolute; top: -
100px; left:
20px; border-
radius: 50%;
box-shadow: 0 0 0
5px #ccc;
</style>
</head>
<body>
<script> let
isFilled = false;
cone.addEventListener("click", () => {
isFilled = !isFilled;
cone.classList.toggle("empty");
if (isFilled) {
cone.style.backgroundColor = "#f90";
document.querySelector(
"body"
).style.backgroundColor = "lightblue";
} else {
cone.style.backgroundColor = "white";
document.querySelector("h1").textContent =
document.querySelector(
"body"
).style.backgroundColor = "#f2f2f2";
});
</script>
</body>
</html>
OUTPUT:
5.a )
AIM: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.
DESCRIPTION:
Destructuring Arrays: Array destructuring is a feature in JavaScript that allows you to unpack
values from an array into separate variables. You can use destructuring to assign array values to
variables with a more concise syntax
Array Methods: JavaScript provides a number of built-in methods for working with arrays. Some
of the most commonly used methods include:
<!DOCTYPE html>
<html>
<head>
<title>Movie Details</title>
</head>
<body>
<h1>Movie Details</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>Starring</th>
<th>Language</th>
<th>Ratings</th>
</tr>
</thead>
<tbody id="movie-details">
</tbody>
</table>
<script>
let movies = [
language: "English",
ratings: 9.3,
},
language: "English",
ratings: 9.2,
},
language: "English",
ratings: 9.0,
},
language: "English",
ratings: 8.9,
},
];
movies.forEach((movie) => {
nameCell.textContent = movie.name;
row.appendChild(nameCell);
starringCell.textContent = movie.starring;
row.appendChild(starringCell);
languageCell.textContent = movie.language;
row.appendChild(languageCell);
ratingsCell.textContent = movie.ratings;
row.appendChild(ratingsCell);
movieTable.appendChild(row);
});
</script>
</body>
</html>
OUTPUT:
5.b )
AIM: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
when
DESCRIPTION:
Async and Await: Async/await is a newer syntax introduced in ES2017 that allows you to write
asynchronous code that looks synchronous. It is built on top of promises and provides a simpler
and more concise way to handle asynchronous operations. Async functions always return a
promise, and the await keyword can be used to wait for the resolution of a promise.
Executing Network Requests using Fetch API: The Fetch API is a modern API for making
network requests in JavaScript. It provides a simple and concise way to make HTTP requests and
handle their responses. The Fetch API returns a promise that resolves to a response object. The
response object contains information about the response, such as the status code and headers.
You can then use the methods provided by the response object to extract the data from the
response, such as text, JSON, or binary data
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<script>
let intervalId;
function startSimulation() {
}, 3000);
function stopSimulation() {
clearInterval(intervalId);
console.log("Simulation stopped.");
</script>
</body>
</html>
OUTPUT:
...
The simulation will continue to generate and display stock prices every three seconds until you
stop it by calling the stopSimulation() function or closing the browser tab.
5.c )
AIM:
Validate the user by creating a login module. Hints: (i) Create a file login.js with a
User class. (ii) Create a validate method with username and password as arguments.
(iii) If the username and password are equal it will return "Login Successful"
Consuming modules means using the exported functions, objects, or variables from the module
in other parts of the program. To consume a module, you need to import it into the file where
you want to use it and then use the imported functions or objects as needed
PROGRAM:
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h1>Login Page</h1>
<form>
<label for="username">Username:</label>
<label for="password">Password:</label>
</form>
<script>
class User {
constructor(username, password) {
this.username = username;
this.password = password;
validate() {
} else {
function validateLogin() {
alert(validationMsg);
</script>
</body>
</html>
OUTPUT:
6.a )
AIM:
DESCRIPTION:
Install Node.js on your computer by downloading the installer from the official Node.js website.
Create a new project directory for your Node.js application.
Initialize the project by running the npm init command in the terminal. This will create a
package.json file for your project, which will contain the project's metadata and dependencies.
Install the required packages and dependencies for your project by running the npm install
command in the terminal. This will install the packages listed in the dependencies section of the
package.json file.
Write the code for your Node.js application using a code editor or IDE.
Run the application by typing node <filename>.js in the terminal, where <filename> is the
name of the main file for your application.
Deploy your application to a web server or hosting platform to make it available to the public.
PROGRAM:
To execute different functions successfully in the Node.js platform, you can follow these general
steps:
1. Create a new file with the .js extension, and give it a meaningful name related to the function(s)
it will contain.
2. Open the file in your preferred code editor, such as VS Code, Atom, or Sublime Text.
3. Begin by defining any required dependencies or modules at the top of the file using the require()
method. For example, if you need to use the built-in fs module to interact with the file system,
you can require it like this:
const fs = require('fs');
4. Define your function(s) within the file. You can use the module.exports object to make your
function(s) available to other files that require them. For example:
function sayHello() { console.log('Hello, world!'); } module.exports = { sayHello: sayHello };
5. In a separate file where you want to use the function(s), require the file that contains them using
the require() method. For example:
const myFunctions = require('./my-functions.js');
6. Call the function(s) using the object you exported from the file. For example:
myFunctions.sayHello();
7. Save both files and run your Node.js application using the node command followed by the
filename. For example:
node app.js
This will execute your application and call your function(s) as expected.
Note that these are general steps, and the specific implementation may vary depending on the
nature of the functions you are working with.
6.b )AIM:
Write a program to show the workflow of JavaScript code executable by creating web
server in Node.js.
DESCRIPTION:
1. Open your preferred code editor and create a new file with a .js extension. Give it a meaningful
name, such as server.js.
2. Require the built-in http module at the top of your file:
const http = require('http');
3. Create a new server instance using the http.createServer() method:
const server = http.createServer((req, res) => { // Code to handle incoming requests });
4. Inside the server instance, define how your server should handle incoming requests. For
example, you can use the res.writeHead() method to set the response header, and res.end()
method to send the response body:
const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain'
}); res.end('Hello, world!'); });
This code will send a 200 OK status code and the message "Hello, world!" to any client that
sends a request to the server.
5. Set the server to listen for incoming requests on a specific port using the server.listen() method:
const port = 3000; server.listen(port, () => { console.log(`Server running at
http://localhost:${port}/`); });
This code will start the server on port 3000 and log a message to the console to confirm that the
server is running.
6. Save your file and start the server by running the following command in your terminal:
node server.js
This will start your server, and it will be ready to receive incoming requests.
Note that this is a very basic example of how to create a web server in Node.js, and there are
many other modules and libraries you can use to create more advanced servers with features such
as routing, middleware, and database integration.
PROGRAM:
res.end('Hello, world!');
// If the request is for /execute, execute some JavaScript code and send the result as the
response
res.end(result);
} else {
res.end('Not found');
});
function executeCode() {
const code = `
function add(a, b) {
return a + b;
`;
return result;
server.listen(port, () => {
});
OUTPUT:
After running the program and navigating to http://localhost:3000/ in your web browser, you
should see the message "Hello, world!" displayed in your browser window.
If you navigate to http://localhost:3000/execute, you should see the result of the executeCode()
function displayed in your browser window: "The result is 5", which is the result of adding 2 and
3 together using the add() function defined in the executeCode() function.
6.c )AIM:
Write a Node.js module to show the workflow of Modularization of Node application.
DESCRIPTION:
Node.js makes it easy to create modular programs by providing a built-in module object that can
be used to define and export modules. To define a module in Node.js, you simply create a new
JavaScript file and define one or more functions or objects that you want to export using the
module.exports object.
PROGRAM:
Sure! Here's an example Node.js module that demonstrates how to modularize a Node
application:
// math.js
function add ( a, b ) { return a + b; }
function subtract ( a, b ) { return a - b; }
module . exports = { add, subtract };
In this module, we define two functions, add() and subtract(), and export them as properties of
an object using the module.exports object. These functions can be used in other parts of our
application by importing this module.
// app.js
const math = require ( './math' ); console . log (math. add ( 2 , 3 )); // 5
console . log (math. subtract ( 5 , 2 )); // 3
In this example, we import the math.js module using the require() function and call its add()
and subtract() functions.
output:
53
This example demonstrates how modularization can help organize our code and make it easier to
reuse across multiple parts of our application. By defining common functionality in modules and
exporting it as needed, we can keep our code clean and maintainable
6.d )AIM:
Write a program to show the workflow of restarting a Node application
DESCRIPTION:
There are several ways to restart a Node.js application, depending on the circumstances.
If you are running your Node application using the node command in your terminal, you can
simply stop the current instance of the application by pressing ctrl + c and then start a new
instance by running the node command again.
If you are running your Node application as a daemon or service, you can typically use a
command-line tool provided by your operating system to restart the service. For example, on
Linux systems, you can use the systemctl command to manage services
PROGRAM:
program that demonstrates how to restart a Node.js application using the pm2 process manager:
// app.js
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, world!');
});
server.listen(3000, () => {
});
process.on('SIGTERM', () => {
server.close(() => {
console.log('Server closed');
process.exit(0);
});
});
process.on('SIGINT', () => {
server.close(() => {
console.log('Server closed');
process.exit(0);
});
});
In this program, we create a simple HTTP server that listens on port 3000 and returns a
"Hello, world!" message when a request is received. We also define two event listeners for
the SIGTERM and SIGINT signals, which are sent when the process is terminated or
interrupted, respectively.
To use pm2 to manage our Node.js process, we need to install it globally using npm:
code
npm install -g pm2
Once pm2 is installed, we can start our Node.js application using the following command:
This will start the application as a background process and give it the name "my-app". We
can then use the following command to view information about the process:
If we need to restart the application for any reason, we can use the following command:
This will gracefully shut down the current instance of the application and start a new
instance in its place. If the application crashes or encounters an error, pm2 will
automatically restart it to keep it running.
OUTPUT OF ABOVE
The output of the program above will be:
Javascript code
Server running at http://localhost:3000/
This indicates that the HTTP server has started and is listening for incoming requests on
port 3000.
If you want to test the HTTP server, you can open a web browser and navigate to
http://localhost:3000/, or you can use a tool like curl to make a request from the command
line:
curl http://localhost:3000/
If you need to restart the Node.js application using pm2, you can use the following
command:
code
pm2 restart my-app
This will gracefully shut down the current instance of the application and start a new
instance in its place. You should see output in the console indicating that the application
has restarted:
code
[PM2] Restarting app... [PM2] App [my-app] restarted
Once the application has restarted, you can test it again to ensure that it is working
correctly.
6.e )AIM:
Create a text file src.txt and add the following data to it. Mongo, Express, Angular,
Node.
DESCRIPTION:
In Node.js, file operations refer to any operation that involves reading from or writing to files on
the file system. Some common file operations include:
Reading from a file: This involves opening a file, reading its contents, and then closing the file.
This can be useful for loading configuration files or reading data from a database.
Writing to a file: This involves opening a file, writing data to it, and then closing the file. This
can be useful for logging data or saving user input to a file.
Appending to a file: This involves opening a file in "append mode", which allows you to add
new data to the end of the file without overwriting any existing data.
Deleting a file: This involves deleting a file from the file system. This can be useful for cleaning
up temporary files or removing files that are no longer needed.
Node.js provides several built-in modules for performing file operations, including the fs
module, which provides a simple and consistent API for working with files. With the fs module,
you can perform operations like reading, writing, appending, and deleting files, as well as
creating and renaming directories.
It's important to note that file operations can be synchronous or asynchronous. Synchronous file
operations block the execution of the program until the operation is complete, while
asynchronous file operations allow the program to continue executing while the operation is in
progress. Asynchronous file operations are generally preferred in Node.js, as they can help
improve the performance and responsiveness of the program.
To create a text file called src.txt and add the data "Mongo, Express, Angular, Node" to it, you
can use the following steps:
1. Create a new folder for your project, if one does not already exist.
2. Open a text editor such as Notepad, or a code editor like VSCode.
3. In the text editor, type the following text:
code
Mongo, Express, Angular, Node
4. Save the file with the name src.txt and make sure to select "All Files" as the file type.
5. Move the src.txt file to the folder for your project.
You have now created a text file called src.txt and added the data "Mongo, Express, Angular,
Node" to it.
The output of the above process would be a text file named src.txt containing the text "Mongo,
Express, Angular, Node".
You can verify that the file has been created and contains the correct text by opening the file in a
text editor or using a command in the terminal or command prompt to view the contents of the
file. For example, in Windows Command Prompt, you can use the command type src.txt to
view the contents of the file in the command prompt
7.a)
AIM:
Implement routing for the AdventureTrails application by embedding the necessary
code in the routes/route.js file.
DESCRIPTION:
Defining a route:
Handling routes:
When a request is made to a defined route, the corresponding handler function will be called.
The handler function takes two parameters: req (the request object) and res (the response object).
PROGRAM:
const express = require('express');
const router = express.Router();
const Trail = require('../models/trail');
console.error(err);
res.status(500).send('Error deleting trail');
} else if (!trail) {
res.status(404).send('Trail not found');
} else {
res.json(trail);
}
});
});
module.exports = router;
Note that we are using the Trail model from the models/trail.js file to interact with the database.
Also, we are using the body-parser middleware to parse incoming request bodies, so make sure
to include the following line in your main app.js file:
This allows us to access the request body as a JavaScript object in our route handlers.
OUTPUT:
[
{
"_id": "60e34e8aa522c0246c5cf6fa",
"name": "Hiking Trail",
"location": "Mountain Range",
"difficulty": "Intermediate",
"length": "5 miles",
"__v": 0
},
{
"_id": "60e34f0a82b19017c2a35611",
"name": "Biking Trail",
"location": "Coastal Region",
"difficulty": "Advanced",
"length": "10 miles",
"__v": 0
}
]
7.b )AIM:
In myNotes application: (i) we want to handle POST submissions. (ii) display
customized error messages. (iii) perform logging.
DESCRIPTION:
Middleware is a function that can be executed before the final request handler is called. It can
intercept the request, perform some operation on it, and pass it on to the next middleware or to
the final request handler.
When a middleware is called, it receives three arguments: req, res, and next. req represents the
request object, res represents the response object, and next is a function that is called to pass
control to the next middleware in the stack.
Middleware functions can be used to perform various operations, such as logging, authentication,
error handling, and data validation. They can also modify the request or response objects, add
new properties or methods to them, or terminate the request-response cycle by sending a
response.
Middleware functions can be chained together using the next function. When a middleware calls
next(), it passes control to the next middleware in the stack. If next() is not called, the request
will be stuck in the current middleware and the response will not be sent.
PROGRAM:
In the above code, we first use the built-in express.json() middleware to parse the JSON body of
POST requests. Then we define a middleware function to handle POST submissions. This
middleware function first extracts the note object from the request body and then validates it. If
the note is invalid, it sends a customized error message to the client. If the note is valid, it logs it
to the console and passes control to the next middleware.
We then define route handlers for displaying all notes and a single note by ID. In the handler for
displaying a single note, we first find the note by ID and then check if it exists. If the note is
found, we send it to the client. If the note is not found, we send a customized error message to
the client.
By using middleware functions, we can modularize our code and separate concerns, making it
easier to maintain and debug.
OUTPUT:
A specific output for the myNotes application without knowing the complete code of the
application. However, the output of the code snippet I provided in the previous message would
be as follows:
When a POST request is made to /notes with a valid JSON body, the note object would be
logged to the console and the response status would be set to 200 with no response body.
When a POST request is made to /notes with an invalid JSON body, the response status would be
set to 400 and the response body would be the string "Title and body are required."
When a GET request is made to /notes, the response body would be an array of all the notes in
the notes array.
When a GET request is made to /notes/:id with a valid ID, the response body would be the note
object with the matching ID.
When a GET request is made to /notes/:id with an invalid ID, the response status would be set to
404 and the response body would be the string "Note not found."
7.c )AIM:
Write a Mongoose schema to connect with MongoDB.
DESCRIPTION:
Connecting to MongoDB with Mongoose: Mongoose is an Object Data Modeling (ODM) library
for MongoDB and it provides a simple way to connect to a MongoDB database using
Mongoose.connect() method. To establish a connection, you need to pass the database URL and
options (if any) as parameters to the Mongoose.connect() method.
Validation Types: Mongoose provides a set of built-in validators that can be used to validate data
before it is saved to the database. These validators include required, min, max, enum, match, and
more. To use a validator, you need to define it as a property of the schema field
Defaults: Mongoose also allows you to set default values for fields in a schema. You can define a
default value for a field by setting the default property of the field.
PROGRAM:
// Update a note by ID
Note.updateOne({ _id: '603dc404bf62f4a4d91a92af' }, { title: 'Updated title' }, (err, result) => {
if (err) {
console.error(err);
} else {
console.log('Note updated successfully:', result);
}
});
// Delete a note by ID
Note.deleteOne({ _id: '603dc404bf62f4a4d91a92af' }, (err, result) => {
if (err) {
console.error(err);
} else {
console.log('Note deleted successfully:', result);
}
});
This code connects to a MongoDB database using Mongoose, defines the Note schema, and
performs various operations on the Note model using Mongoose methods such as .save(), .find(),
.findById(), .updateOne(), and .deleteOne(). The output of the code will depend on the specific
operations being performed and the state of the MongoDB database.
7.d )AIM:
Write a program to wrap the Schema into a Model object.
DESCRIPTION:
In the context of an Express application, models are typically used to represent data and define
the interactions with a database. A model typically corresponds to a database table and is
responsible for defining the schema and providing methods for interacting with the data.
PROGRAM:
const mongoose = require('mongoose');
OUTPUT:
The output of the program will depend on the specific database operations being performed.
Here's an example of the output you might see when running a program that retrieves all users
from the database using the find() method of the User model object:
User.find({}, (err, users) => {
if (err) {
console.error(err);
} else {
console.log(users);
}
});
Assuming there are three users in the database, the output might look something like this:
[
{ _id: '609ed60b70c0f9384409e8a6', name: 'John Doe', age: 30, email:
'[email protected]' },
{ _id: '609ed60b70c0f9384409e8a7', name: 'Jane Smith', age: 25, email:
'[email protected]' },
{ _id: '609ed60b70c0f9384409e8a8', name: 'Bob Johnson', age: 40, email:
'[email protected]' }
]
This output shows an array of three user objects, each with an ID, name, age, and email.
8.a )AIM:
Write a program to perform various CRUD (Create-Read-Update-Delete) operations
using Mongoose library functions.
DESCRIPTION:
CRUD (Create, Read, Update, Delete) operations are common operations used in web
development. In Express.js, we can perform CRUD operations using HTTP methods like GET,
POST, PUT, and DELETE.
PROGRAM:
// Define schema
name: String,
email: String,
});
// Define model
user.save((err) => {
if (err) console.error(err);
});
if (err) console.error(err);
console.log(users);
});
// Read user by ID
const id = '60519d4b4c4b5e5b5ca5e5d5';
if (err) console.error(err);
console.log(user);
});
// Update user
if (err) console.error(err);
console.log(user);
});
// Delete user
if (err) console.error(err);
});
OUTPUT:
_id: 60519d3c5da7cb5b37c358a7,
name: 'John',
email: '[email protected]',
__v: 0
_id: 60519d3c5da7cb5b37c358a7,
name: 'John',
email: '[email protected]',
__v: 0
_id: 60519d3c5da7cb5b37c358a7,
name: 'Jane',
email: '[email protected]',
__v: 0
8.b )AIM:
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
DESCRIPTION:
API development in Express.js involves creating API endpoints that can handle incoming HTTP
requests, process them, and send back appropriate responses. The API endpoints can be used by
clients to access and manipulate data or perform other operations.
PROGRAM:
mongoose.connect('mongodb://localhost/myNotes');
try {
if (!note) {
res.json(note);
} catch (err) {
console.error(err);
});
app.listen(3000, () => {
});
OUTPUT:
As this code is meant to be run on a server, there won't be any visible output on the console.
However, we can test the API using a tool like Postman or a web browser.
Assuming that the API is running on localhost:3000, we can send a GET request to the endpoint
/notes/7555 by visiting the URL http://localhost:3000/notes/7555 in a web browser or using
Postman.
If a note with ID 7555 exists in the database, its details will be returned as a JSON response. For
example:
"_id": "6159078f7b9ca2d3fcf3b2c8",
"createdAt": "2021-10-03T10:34:23.950Z",
"updatedAt": "2021-10-03T10:34:23.950Z",
"__v": 0
}If a note with ID 7555 doesn't exist in the database, a 404 status code will be returned along
with a message. For example
8.c )AIM:
Write a program to explain session management using cookies.
DESCRIPTION:
Session management and cookies are important concepts in web development for maintaining
user state and improving user experience.
Sessions are used to maintain user state across multiple requests. When a user logs in to a
website, a session is created on the server, and a unique session ID is generated and stored in a
cookie on the user's browser. This session ID is used to identify the user's session on subsequent
requests, allowing the server to retrieve session data and maintain user state. Sessions can be
used to store user-specific data such as user ID, username, user preferences, etc.
Cookies are small text files that are stored on the user's browser. They are used to store user-
specific data such as login credentials, user preferences, and session IDs. Cookies can be set by
the server or by client-side scripts, and they are sent to the server with each request. Cookies can
also be used to store information about the user's activity on the website, such as the pages they
have visited, the items they have added to their cart, etc.
Together, sessions and cookies enable web applications to maintain user state, personalize the
user experience, and provide a more seamless user experience.
PROGRAM:
app.use(cookieParser());
app.use(session({
secret: 'mysecretkey',
resave: false,
saveUninitialized: true,
}));
res.send(`
<h1>Login</h1>
<label for="username">Username:</label>
<label for="password">Password:</label>
<button type="submit">Submit</button>
</form>
`);
});
req.session.userId = 1;
res.send('<p>Login successful!</p>');
} else {
});
if (userId) {
} else {
});
req.session.destroy();
});
app.listen(port, () => {
});
OUTPUT:
8.d )AIM:
Write a program to explain session management using sessions.
DESCRIPTION:
In web development, a session is a way to store and persist user data across multiple requests
from the same user. Sessions allow a web application to keep track of user state and information,
such as login credentials, shopping cart contents, and user preferences.
When a user logs in or interacts with a web application, the server creates a unique session for
that user, which is associated with a session ID. The session ID is then stored as a cookie in the
user's browser, and the server can use it to retrieve the corresponding session data for that user
on subsequent requests.
PROGRAM:
app.use(session({
secret: 'mysecretkey',
resave: false,
saveUninitialized: true
}));
if (sessionData.views) {
sessionData.views++;
res.setHeader('Content-Type', 'text/html');
res.write('<p><a href="/logout">Logout</a></p>');
res.end();
} else {
sessionData.views = 1;
res.send('Welcome to the session demo! Refresh the page to increase the view count.');
});
req.session.destroy((err) => {
if (err) {
console.log(err);
} else {
res.redirect('/');
});
});
app.listen(3000, () => {
});
OUTPUT:
Welcome to the session demo! Refresh the page to increase the view count.
Number of views: 2
Logout
8.e )AIM:
Implement security features in myNotes application
DESCRIPTION:
Security is a critical concern for any web application, and it is essential to ensure that the
application is protected against common web vulnerabilities such as cross-site scripting (XSS),
cross-site request forgery (CSRF), and other attacks. In addition, it is important to ensure that
sensitive user data is encrypted in transit and at rest, and that the application is protected against
attacks like SQL injection.
One of the ways to enhance the security of an Express.js application is by using middleware.
Middleware functions are functions that have access to the request and response objects, and can
modify them or perform other actions based on the needs of the application.
Helmet is a collection of middleware functions that help to improve the security of an Express.js
application. Helmet includes middleware functions that set various HTTP headers that can help
protect against attacks such as XSS and CSRF, as well as middleware that helps to secure
cookies and enable HTTP Strict Transport Security (HSTS).
PROGRAM:
1. Authentication: Implement a user authentication system to ensure that only authorized users can
access and modify their notes. This can be done using third-party authentication services like
OAuth or by creating a custom authentication system.
passport.use(new LocalStrategy(
});
));
app.post('/login',
function(req, res) {
res.redirect('/notes');
});
2. Authorization: Once the user is authenticated, implement an authorization system to ensure that
users can only access and modify their own notes. This can be done using role-based access
control or by associating notes with specific users in the database.
title: String,
body: String,
});
module.exports = Note;
3. Encryption: Ensure that user data is encrypted both in transit and at rest. This can be done using
SSL/TLS encryption for in-transit data and data encryption at the database level.
const fs = require('fs');
httpsServer.listen(443);
4. Helmet middleware: Finally, use the Helmet middleware to implement additional security
measures like setting various HTTP headers to protect against attacks such as XSS and CSRF.
app.use(helmet());
app.listen(3000);
9.a )
AIM:
On the page, display the price of the mobile-based in three different colors.
Instead ofusing the number in our code, represent them by string values like
GoldPlatinum,PinkGold, SilverTitanium.
DESCRIPTION:
TypeScript is developed and maintained by Microsoft and is open-source. It can be used to build
large-scale applications in both client-side and server-side environments. TypeScript code is
transpiled into JavaScript code, which can then be run on any browser or server that supports
JavaScript.
PROGRAM:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
</div>
</body>
</html>
OUTPUT:
9.b )
AIM:
Define an arrow function inside the event handler to filter the product array
with theselected product object using the productId received by the function.
Pass the selectedproduct object to the next screen.
DESCRIPTION:
In TypeScript, functions are first-class citizens, which means that they can be treated like any
other value or variable. This allows for greater flexibility and expressiveness when defining
functions in TypeScript.
To define a function in TypeScript, you use the function keyword, followed by the function
name and a set of parentheses that contain any parameters that the function takes. The function
body is then enclosed in curly braces, and the return type is specified after the closing
parenthesis of the parameter list, using a colon followed by the return type
PROGRAM:
interface Product {
productId: number;
name: string;
price: number;
];
setSelectedProduct(product ?? null);
// Navigate to the product details screen with the selected product object
return (
<div>
<h1>Product List</h1>
<ul>
{products.map((product) => (
<li key={product.productId}>
{product.name} (${product.price})
</button>
</li>
))}
</ul>
{selectedProduct && (
<div>
<h2>Selected Product</h2>
<p>{selectedProduct.name} (${selectedProduct.price})</p>
View Details
</button>
</div>
)}
</div>
);
OUTPUT:
Product List
- Product 1 ($10)
- Product 2 ($20)
- Product 3 ($30)
Selected Product
Product 2 ($20)
[View Details]
9.c )
AIM:
Consider that developer needs to declare a function - getMobileByVendor
whichaccepts string as input parameter and returns the list of mobiles.
DESCRIPTION:In TypeScript, parameter types and return types are used to specify the data
types of the input and output of a function. They can be explicitly defined using type
annotations.Parameter types specify the data type of the function's input parameters. They are
placed after the parameter name, separated by a colon
PROGRAM:
interface Mobile {
brand: string;
model: string;
price: number;
];
console.log(appleMobiles);
9.d )AIM:
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
DESCRIPTION:
Arrow functions are a shorthand syntax for writing functions in TypeScript (and JavaScript).
Arrow functions provide a concise way to define functions using the => syntax. Arrow functions
have a number of advantages over traditional function syntax. They are more concise, making
code easier to read and write. They also have a lexical this binding, which means that the this
value inside the function is the same as the this value outside the function.
PROGRAM:
interface Manufacturer {
id: number;
price: number;
{ id: 1, price: 10 },
{ id: 2, price: 15 },
{ id: 3, price: 20 },
{ id: 4, price: 25 }
];
console.log(filteredIds);
Output: [3, 4]
9.e)
AIM:
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
DESCRIPTION:
Optional and default parameters are features in TypeScript (and JavaScript) that allow
developers to define function parameters with optional or default values.Optional parameters are
indicated by adding a question mark (?) after the parameter name in the function declaration.
Optional parameters can be omitted when calling the function, and will be assigned the value
undefined if not provide Default.Parameters are indicated by assigning a default value to the
parameter in the function declaration. Default parameters will be assigned the default value if no
value is provided when calling the function
PROGRAM:
interface Mobile {
id: number;
manufacturer: string;
model: string;
];
if (id) {
} else {
return filteredMobiles;
10.a )
AIM:
Implement business logic for adding multiple Product values into a cart
variable which
is type of string array.
DESCRIPTION:
A rest parameter is a feature in TypeScript (and JavaScript) that allows developers to define a
function parameter that captures all remaining arguments passed to the function as an array. The
rest parameter is indicated by prefixing the last function parameter with three dots (...)
PROGRAM:
Output:
10.b )
AIM:
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.
DESCRIPTION:
In TypeScript, an interface is a way to define a contract for an object, specifying the properties
and methods that the object should have. An interface defines the shape of an object, without
providing any implementation details.
To create an interface in TypeScript, you can use the interface keyword, followed by the name
of the interface and its properties and methods.
PROGRAM:
interface Product {
productId: number;
productName: string;
addProduct(newProduct);
10.c )
AIM:
Declare an interface named - Product with two properties like productId and
productName with the number and string datatype and need to implement
logic to populate the Product details.
DESCRIPTION:
Duck typing is a concept in TypeScript (and other programming languages) that refers to
checking for the presence of certain properties or methods in an object, rather than its actual type
or class. The term "duck typing" comes from the saying, "If it looks like a duck, swims like a
duck, and quacks like a duck, then it probably is a duck."
In TypeScript, duck typing is often used in cases where multiple classes or interfaces share a
similar set of properties or methods. Instead of explicitly checking for the type or class of an
object, you can check if it has the necessary properties or methods to fulfill the requirements of a
particular piece of code.
PROGRAM:
interface Product {
productId: number;
productName: string;
}
Output:
Added product Laptop with ID 123
10.d )
AIM: Declare an interface with function type and access its value.
DESCRIPTION:
In TypeScript, function types refer to the types of functions, including their input parameters and
output values. Function types can be used to define the type signature of a function, allowing for
better type checking and error handling.
To define a function type, you can use the syntax (param1: type1, param2: type2, ...) =>
returnType, where param1, param2, etc. are the parameter names, type1, type2, etc. are the
parameter types, and returnType is the return type of the function.
PROGRAM:
Output: 5
11.a )
AIM:
Declare a productList interface which extends properties from two other
declared
interfaces like Category,Product as well as implementation to create a
variable of this
interface type.
DESCRIPTION:
In TypeScript, interfaces can be extended by other interfaces using the extends keyword. This
allows you to create new interfaces that inherit the properties and methods of an existing
interface, while also adding new properties and methods of their own.
To extend an interface, simply define a new interface and use the extends keyword to specify the
parent interface that it inherits from
PROGRAM:
interface Category {
id: number;
name: string;
}
interface Product {
id: number;
name: string;
price: number;
}
console.log(myProductList);
Output:
{ id: 1, name: 'T-Shirt', price: 19.99, quantity: 10 }
11.b)
AIM:
Consider the Mobile Cart application, Create objects of the Product class and
place
them into the productlist array.
DESCRIPTION:
In TypeScript, classes are used to define object blueprints with properties and methods. They
provide a way to create objects that have the same structure and behavior, making it easier to
manage and manipulate complex data.
To define a class in TypeScript, you use the class keyword followed by the name of the class.
PROGRAM:
class Product {
name: string;
price: number;
console.log(productList);
Output:
[Product { name: 'iPhone X', price: 999 }, Product { name: 'Samsung Galaxy S21', price:
799 }, Product { name: 'Google Pixel 5', price: 699 }]
11.c )
AIM:
Declare a class named - Product with the below-mentioned declarations: (i)
productId as number property (ii) Constructor to initialize this value (iii)
getProductId method to return the message "Product id is <<id value>>".
DESCRIPTION:
In TypeScript, the constructor method is a special method that is used to create and initialize
objects created from a class. It is called automatically when a new object is created using the
new keyword and can be used to set initial values for object properties.
PROGRAM:
class Product {
productId: number;
constructor(productId: number) {
this.productId = productId;
}
getProductId() {
return `Product id is ${this.productId}`;
}
}
Output:
Product id is 123
11.d )AIM:
Create a Product class with 4 properties namely productId, productName,
productPrice, productCategory with private, public, static, and protected
access modifiers and accessing them through Gadget class and its methods.
DESCRIPTION:
In TypeScript, access modifiers are used to control the accessibility of class members (properties
and methods). There are three access modifiers available: public, private, and protected.
public members are accessible from anywhere, both within and outside of the class.private
members are only accessible within the class that defines them.protected members are
accessible within the class that defines them and any subclasses.
PROGRAM:
class Product {
private productId: number;
public productName: string;
protected productPrice: number;
static productCategory: string = "Electronics";
getProductDetails() {
return `Product: ${this.productName} (id: ${this.productId}, price:
${this.productPrice})`;
}
}
class Gadget {
constructor(private product: Product) {}
getProductCategory() {
return Product.productCategory;
}
getProductDetails() {
return this.product.getProductDetails();
}
}
12.a )AIM:
Create a Product class with 4 properties namely productId and methods to
setProductId() and getProductId().
DESCRIPTION:
In TypeScript, properties and methods are used to define the state and behavior of a class.
Properties represent the state of an object and are used to store data. They can be declared with
different access modifiers (public, private, protected) to control their visibility and
accessibility.
Methods represent the behavior of an object and are used to perform operations on the object's
data. They can be declared with different access modifiers to control their visibility and
accessibility, and can also accept parameters and return values.
Properties and methods are accessed using the dot notation, where the property or method name
is followed by a dot (.) and the name of the object instance.
PROGRAM:
class Product {
private productId: number;
constructor(productId: number) {
this.setProductId(productId);
}
setProductId(productId: number) {
this.productId = productId;
}
getProductId() {
return this.productId;
}
}
product1.setProductId(456);
console.log(product1.getProductId()); // Output: 456
12.b )AIM:
Create a namespace called ProductUtility and place the Product class
definition in it. Import the Product class inside productlist file and use it.
DESCRIPTION:
In TypeScript, namespaces are used to group related code into a single container to avoid naming
collisions with code in other namespaces or in the global scope.
To create a namespace, we use the namespace keyword followed by the name of the namespace
and a set of curly braces containing the code that belongs to the namespace.
For example, suppose we have a set of utility functions for working with arrays. We can group
these functions into a namespace called ArrayUtils
PROGRAM:
namespace ProductUtility {
export class Product {
private productId: number;
constructor(productId: number) {
this.setProductId(productId);
}
setProductId(productId: number) {
this.productId = productId;
}
getProductId() {
return this.productId;
}
}
product1.setProductId(456);
console.log(product1.getProductId()); Output: 456
12.c )AIM:
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.
DESCRIPTION:
In TypeScript, modules are used to organize code into reusable and maintainable units. A module
can contain variables, functions, classes, interfaces, and other declarations, and can be used in
other modules or applications.
To create a module in TypeScript, you can use the export keyword to export variables,
functions, or classes from a file. For example, to export a function add from a file math.ts
PROGRAM:
12.d )AIM:
Create a generic array and function to sort numbers as well as string values.
DESCRIPTION:
Generics in TypeScript is a powerful feature that allows you to create reusable components that
can work with a variety of data types. It allows you to write more flexible and type-safe code,
while still providing the flexibility to work with different data types.
Type Parameters: Type parameters are used to define a generic type that can work with any data
type. A type parameter is a placeholder for a type that will be provided later when the function,
class or interface is used. Type parameters are enclosed in angle brackets (<>) and are placed
immediately after the name of the function, class or interface
Generic Functions: Generic functions are functions that are defined with one or more type
parameters. These type parameters can be used in the function's signature, allowing the function
to work with a wide variety of data types.
Generic Constraints: Generic constraints are used to restrict the types that a type parameter can
be replaced with. This is useful when you want to enforce certain properties on the data type
being used
PROGRAM:
productUtils.ts
mobileCart.ts
import { calculateTotalPrice } from './productUtils';
class Product {
constructor(private productId: number, private productName: string, private
productPrice: number) {}
getProductDetails() {
return `Product ID: ${this.productId}\nProduct Name: ${this.productName}\nProduct
Price: $${this.productPrice}\n`;
}
getTotalPrice(quantity: number) {
return calculateTotalPrice(quantity, this.productPrice);
}
}
const quantity1 = 2;
const quantity2 = 3;
OUTPUT:
Product ID: 1
Product Name: iPhone
Product Price: $999
Quantity: 2
Total Price: $1998
Product ID: 2
Product Name: Samsung Galaxy
Product Price: $799
Quantity: 3
Total Price: $2397