Mean Stack Technologies Lab Manual
Mean Stack Technologies Lab Manual
Date:
Aim:
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.
HTML&Javascript
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.
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>
<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 © 2023</p>
</footer>
</body>
</html>
Result:
The code for HTML5 Elements is executed successfully without any errors.
References:
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
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>
<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>
<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>
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>
</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 © 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>
<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>
Result:
The code for HTML5-Attributes,Elements,Media, Iframe is executed successfully without any
errors.
References:
Type of Identifiers
Exp. No.:
Date:
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).
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:
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
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
Result:
The code for Type of Identifiers in javascriptis executed successfully without any errors.
References:
Date:
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.
Software Required:
HTML&Javascript
Theory:
Certainly, let's discuss primitive and non-primitive data types in JavaScript:
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:
Number:
For example:
Boolean:
For example:
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:
Symbol (ES6):
For example:
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.
For example:
const person = {
name: "Alice",
age: 30,
isStudent: false
};
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
console.log(`Language: ${language}`);
console.log(`Ratings: ${ratings}`);
Result:
The code for primitive and non primitive data types in javascriptis executed successfully without any
errors.
References:
Date:
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.
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)
Example:
int a = 10;
int b = 3;
int sum = a + b;
// sum is 13
Assignment Operators:
= (Assignment)
Example:
int x = 5;
x += 3; // x is now 8
Comparison Operators:
== (Equal to)
Example:
int num2 = 5;
Logical Operators:
|| (Logical OR)
! (Logical NOT)
Example:
booleanisStudent = true;
booleanhasBooks = false;
++ (Increment by 1)
-- (Decrement by 1)
Example:
int count = 5;
| (Bitwise OR)
^ (Bitwise XOR)
~ (Bitwise NOT)
Example:
int num1 = 5;
int num2 = 3;
// result is 1
Example:
Example:
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 numberOfTickets = 5;
// apply discount
// display results
Result:
The code of types of operators in javascript is executed successfully without any errors.
References:
Types of Statements
Exp. No.:
Date:
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.
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:
Example:
Assignment Statements:
Example:
Expression Statements:
Example:
Example:
Conditional Statements:
Conditional statements allow you to execute different code blocks based on specific conditions.
If Statements:
Example:
If-else Statements:
Executes one block of code if a condition is true and another if it's false.
Example:
} else {
Example:
System.out.println("A grade.");
System.out.println("B grade.");
System.out.println("C grade.");
} else {
System.out.println("F grade.");
Switch Statements:
Example:
int dayOfWeek = 3;
switch (dayOfWeek) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
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
let numTickets = 3;
let totalPrice;
if (numTickets<= 2) { // if statement
switch (numTickets) {
case 3:
break;
case 4:
break;
case 5:
break;
default:
if (totalPrice) { // if statement
Result:
The code for types of statements in javascript is executed successfully without any errors.
References:
Types of Loops
Exp. No.:
Date:
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.
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:
Syntax:
// Code to be repeated
Example:
While Loop:
Used when you want to repeat a block of code as long as a condition is true.
Syntax:
while (condition) {
// Code to be repeated
Example:
int count = 0;
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 {
num++;
Syntax:
Example:
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;
if (numOfTickets> 5) {
} else {
if (numOfTickets<= 2) {
totalPrice += ticketPrice;
} else {
Result:
The code for types of loops in javascript is executed successfully without any errors.
References:
Date:
Aim:
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.
Function Declaration:
Syntax:
function functionName(parameters) {
// Code to be executed
Function Expression:
Syntax:
constfunctionName = function(parameters) {
// Code to be executed
};
Syntax:
// Code to be executed
};
// Function Declaration
function greet(name) {
// Function Expression
return a + b;
};
// Arrow Function
// Invoking Functions
Function Parameters:
Functions can accept parameters (inputs) that are used in the function's code.
function greet(name) {
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();
outerFunction();
// Outputs:
// "Outer function"
// "Inner function"
Built-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() {
localScopeExample();
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
function bookTickets(numSeats) {
let totalPrice = 0;
function calculatePrice(numSeats) {
let price = 0;
if (numSeats<= 2) {
} else if (numSeats>= 6) {
return;
} else {
return price;
totalPrice = calculatePrice(numSeats);
// Example usage
bookTickets(2);
bookTickets(7);
bookTickets(4);
Result:
The code for types of functions in java script is executed successfully without any errors.
References:
Date:
Aim:
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:
// Constructors
// Methods
Public:
Access modifier indicating that the class is accessible from any other class.
Classname: The name of your class, which should start with an uppercase letter.
String name;
Int age;
// Constructor
This.name = name;
This.age = age;
// Method
To use a class, you create objects or instances of that class using the new keyword:
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.
String studentid;
This.studentid = studentid;
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.
You can create instances of the subclass and use its methods:
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;
}}
super(name, age);
this.role = role;
}}
Result:
The code for creating and inheriting classes in javascript is executed successfully without any
errors.
References:
Date:
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.
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.
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:
Button.addeventlistener('click', function() {
Alert('Button clicked!');
});
In this example:
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.
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>
</div>
Java script
constticketPrice = 150;
function calculateTotalPrice(numTickets) {
let totalPrice;
if (numTickets> 2 &&numTickets< 6) {
} else if (numTickets<= 2) {
} else {
return totalPrice;
function handleBookBtnClick() {
constnumTicketsInput = document.getElementById("num-tickets");
constnumTickets = parseInt(numTicketsInput.value);
consttotalPrice = calculateTotalPrice(numTickets);
if (totalPrice) {
constbookBtn = document.getElementById("book-btn");
bookBtn.addEventListener("click", handleBookBtnClick);
Result:
The code for In-builtEventsandHandlers in javascript is executed successfully without any errors.
References:
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:
Types of Objects:
Creating Objects:
You can create objects using object literals, constructors, or classes (in modern JavaScript).
const person = {
name: 'Alice',
age: 30
};
// Using a constructor
this.name = name;
this.age = age;
The spread operator (...) can be used to combine and clone objects.
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
Destructuring Objects:
Destructuring allows you to extract values from objects and assign them to variables easily.
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.
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.
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>
<style>
body {
background-color: #f0f0f0;
.cone {
width: 150px;
height: 300px;
background-color: white;
position: relative;
.scoop {
width: 120px;
height: 120px;
background-color: #ffa500;
border-radius: 50%;
position: absolute;
top: -60px;
left: 15px;
.scoop.filled {
height: 150px;
top: -90px;
h1 {
text-align: center;
font-size: 36px;
margin-top: 0;
color: #333;
p{
text-align: center;
font-size: 24px;
color: #666;
.btn {
display: block;
width: 100px;
height: 40px;
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>
<script src="app.js"></script>
</body>
</html>
JavaScript (app.js):
function toggleScoop() {
filled = !filled;
scoop.classList.toggle('filled');
if (filled) {
body.style.backgroundColor = '#ffa500';
} else {
body.style.backgroundColor = '#f0f0f0';
Result:
The code for Types of Objects in javascript is executed successfully without any errors.
References:
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:
int[] numbers;
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:
Accessing Arrays:
You can access elements of an array by their index, which starts at 0 for the first element. For
example:
Array Methods:
Java provides various methods and operations for working with arrays. Some common array
methods include:
Sorting: You can use the Arrays.sort() method to sort an array in ascending order.
Searching: You can use methods like Arrays.binarySearch() to search for an element in a sorted
array.
Copying Arrays: To copy the contents of one array to another, you can use System.arraycopy() or
other methods.
Iterating through Arrays: You can use loops (e.g., for or foreach) to iterate through array elements.
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 = [
language: 'English',
rating: 9.2
},
name: 'Parasite',
language: 'Korean',
rating: 8.6
},
language: 'English',
rating: 8.0
},
name: 'Inception',
language: 'English',
rating: 8.8
},
language: 'Japanese',
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 = [
language: 'English',
rating: 9.2
},
name: 'Parasite',
language: 'Korean',
rating: 8.6
},
language: 'English',
rating: 8.0
},
name: 'Inception',
language: 'English',
rating: 8.8
},
language: 'Japanese',
rating: 8.6
];
movies.forEach(movie => {
movieElement.innerHTML = `
<h2>${movie.name}</h2>
<p>Language: ${movie.language}</p>
<p>Rating: ${movie.rating}</p>
`;
moviesContainer.appendChild(movieElement);
});
</script>
</body>
</html>
Result:
The code for array method in javascript is executed successfully without any errors.
References:
Exp. No.:
Date:
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.
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:
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.
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 simulateStockPriceChange() {
function startPeriodicUpdates(interval) {
setTimeout(() => {
clearInterval(intervalId);
console.log('Updates stopped');
startPeriodicUpdates(3000);
Result:
The code for Asynchronous Programming, Callbacks, Promisesinjavascript is executed
successfully without any errors.
References:
Date:
Aim:
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).
math.js:
// Exporting a function
return a + b;
};
// Exporting a variable
exports.PI = 3.14159265359;
math.js:
// Exporting a function
return a + b;
// Exporting a variable
Consuming Modules:
Once you've created a module, you can import and use its exported values in other parts of your
code.
main.js:
main.js:
import { add, PI } from './math'; // Import specific values from the math module
math.js:
return a + b;
main.js:
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.
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;
} else {
module.exports = {
User,
validate
};
Result:
The code for Creating and Consuming Modules in javascript is executed successfully without any
errors.
References:
Date:
Aim:
Software Required:
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.
You can start by creating a directory for your Node.js application and navigating to it in your
terminal.
mkdir my-node-app
cd my-node-app
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
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.
console.log("Hello, Node.js!");
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
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:
This command will download and install the express package, and it will be added to your
project's package.json file as a dependency.
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:
Date:
Aim:
Write a program to show the workflow of JavaScript code executable by creating web server in
Node.js.
Software Required:
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.
First, create a new directory for your Node.js web server project:
mkdir my-node-server
cd my-node-server
npminit -y
The http module is a built-in module in Node.js, so you don't need to install it separately.
Create a JavaScript file (e.g., server.js) and write the code to create a simple web server:
res.end('Hello, World!\n');
});
server.listen(port, () => {
});
In this script:
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.
Run the web server by executing the server.js script using Node.js:
node server.js
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:
response.write('Hello World!');
response.end();
server.listen(port, () => {
});
node server.js
Result:
The code of Creating a Web Server in node.js is executed successfully without any errors.
References:
Date:
Aim:
Software Required:
Creating Modules:
Start by creating a JavaScript file for your module. For example, let's create a module named
math.js:
// math.js
module.exports = {
add,
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
Here, we've imported the math.js module and used its functions.
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.
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.
Break your application into smaller, focused modules that each handle a specific task or
functionality.
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
const mathModule = {
add: function(a, b) {
return a + b;
},
subtract: function(a, b) {
return a - b;
},
multiply: function(a, b) {
return a * b;
},
divide: function(a, b) {
return a / b;
};
module.exports = mathModule;
Javascript:
console.log(`5 + 10 = ${sum}`);
console.log(`15 - 7 = ${difference}`);
console.log(`3 * 4 = ${product}`);
console.log(`20 / 5 = ${quotient}`);
Result:
The code for Modular Programmingin node.js is executed successfully without any errors.
References:
Date:
Aim:
Software Required:
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:
On Windows, you can use the Task Manager to find and 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.
On Unix-based systems (Linux, macOS), use the kill command with the PID:
kill -9 <PID>
On Windows, open the Task Manager, find the Node.js process, and select "End Task" or "End
Process."
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:
For Forever:
Restarting the application will launch a new Node.js process with the updated code or
configuration.
To ensure that the application has restarted successfully, you can check the logs or access the
application to verify its functionality.
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:
res.write('Hello, World!');
res.end();
});
server.listen(3000, () => {
});
This will start the server and also start monitoring the app.js file for changes.
Result:
The code for Restarting Node Applicationsin node.js is executed successfully without any
errors.
References:
Date:
Aim:
Create a text file src.txt and add the following data to it. Mongo, Express, Angular,nNode.
Software Required:
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).
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
You can use a text editor like nano, vim, or touch to create and edit the file. Here, we'll use nano
for simplicity:
nano src.txt
This will open the src.txt file in the nano text editor.
To save the file in nano, press Ctrl + O, then press Enter. To exit, press Ctrl + X.
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:
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:
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:
});
res.send('Contact us at [email protected]');
});
app.listen(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:
});
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:
});
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.
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:
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:
});
});
// Fetch and display information about the trail with the specified ID
});
module.exports = router;
In your main app.js file, import the route.js file and use it to set up routes:
app.use('/', routes);
app.listen(PORT, () => {
});
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.
Result:
The code for Route, Query Parametersin express.js is executed successfully without any errors.
References:
Types of MiddleWares
Exp. No.:
Date:
Aim:
myNotes application: (i) we want to handle POST submissions. (ii) display customized error
messages. (iii) perform logging..
Software Required:
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:
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:
app.use(bodyParser.json());
const noteText = req.body.note; // Assuming the POST data contains a 'note' field
});
app.listen(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.
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:
if (!noteId) {
} else {
// 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.
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 an error
// Logging information
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 fs = require('fs');
app.use(bodyParser.json());
if (!title || !content) {
// ...
});
console.error(err.stack);
});
app.listen(3000, () => {
});
Result:
The code for Middleware works in express.js is executed successfully without any errors.
References:
Date:
Aim:
Module Name: Connecting to MongoDB with Mongoose, Validation Types and Defaults
Software Required:
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.
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
You need to establish a connection to your MongoDB database using Mongoose. Here's how you
can do it:
.then(() => {
console.log('Connected to MongoDB');
})
.catch((error) => {
});
Replace 'your_database_url' with the actual connection URL for your MongoDB database.
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.
username: {
type: String,
},
email: {
type: String,
required: true,
unique: true,
validate: {
return /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(value);
},
},
},
createdAt: {
type: Date,
},
});
module.exports = User;
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.
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:
username: 'john_doe',
email: '[email protected]',
});
newUser.save()
.then((user) => {
})
.catch((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.
Program:
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,
min: 18,
max: 100
},
createdAt: {
type: Date,
default: Date.now
});
module.exports = User;
Result:
The code for Connecting to Mongo DB with Mongoosein express.js is executed successfully
without any errors.
References:
Models
Exp. No.:
Date:
Aim:
Software Required:
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 {
this.title = title;
this.author = author;
this.ISBN = ISBN;
displayInfo() {
console.log(`${this.title} by ${this.author}`);
const myBook = new Book('The Great Gatsby', 'F. Scott Fitzgerald', '978-0743273565');
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.
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:
constructor(props) {
super(props);
this.state = {
count: 0,
};
increment() {
render() {
return (
<div>
<p>Count: {this.state.count}</p>
</div>
);
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
name: {
type: String,
required: true,
},
age: {
type: Number,
min: 0,
max: 120,
default: 18,
},
email: {
type: String,
required: true,
unique: true,
match: /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/,
},
});
module.exports = Person;
Result:
The code for Models in express.js is executed successfully without any errors.
References:
CRUD Operations
Exp. No.:
Date:
Aim:
Software Required:
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:
myArray.push('New item');
Creating Objects:
const myObject = {
key1: 'value1',
key2: 'value2',
};
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:
const myObject = {
name: 'John',
age: 30,
};
Querying Databases/APIs:
Retrieve data from databases or APIs by making GET requests with appropriate queries or
parameters.
3. Update (U):
Updating data involves modifying existing data. Here are some common methods:
Modifying Arrays:
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:
Delete elements from an array, often using methods like splice() or pop().
You can delete properties from an object using the delete keyword.
const myObject = {
name: 'John',
age: 30,
};
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
mongoose.connect('mongodb://localhost/mydatabase',
.catch((error) =>console.error(error));
name: {
type: String,
required: true
},
age: Number,
grade: {
type: Number,
min: 0,
max: 100
});
name: 'John',
age: 18,
grade: 80
});
john.save()
.catch((error) =>console.error(error));
Student.find()
.catch((error) =>console.error(error));
// Find a student by ID
Student.findById('605aa10d7f80ba4e9c32dc25')
.catch((error) =>console.error(error));
// Update a student by ID
Student.findByIdAndUpdate('605aa10d7f80ba4e9c32dc25', { age: 19 })
.catch((error) =>console.error(error));
// Delete a student by ID
Student.findByIdAndDelete('605aa10d7f80ba4e9c32dc25')
.catch((error) =>console.error(error));
Result:
The code for CRUD Operationsin express.js is executed successfully without any errors.
References:
API Development
Exp. No.:
Date:
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 bas.
Software Required:
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.
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/
Create a new directory for your project and navigate to it in your terminal.
npminit
To create an API, you'll need a web framework like Express.js. Install it as a project
dependency:
});
app.listen(port, () => {
});
In this example, we've created a simple Express.js server with one API route ("/api/hello")
that returns a JSON response.
node app.js
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:
});
const newItem = req.body.item; // Assuming the client sends JSON data with an 'item'
property
});
// Define other API routes as needed for updating and deleting items
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:
app.use(bodyParser.json());
Implement error handling middleware to manage errors gracefully and provide meaningful
responses to clients:
console.error(err.stack);
});
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.
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:
// Fetch note by ID
try {
if (!note) {
res.send(note);
} catch (error) {
res.status(500).send(error.message);
});
// Update note by ID
try {
if (!note) {
res.send(note);
} catch (error) {
res.status(500).send(error.message);
});
module.exports = router;
Result:
The code for API Developmentin express.js is executed successfully without any errors.
References:
Date:
Aim:
Software Required:
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.
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.
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');
});
Result:
The code for Session management, Cookiesin express.js is executed successfully without any
errors.
References:
Sessions
Exp. No.:
Date:
Aim:
Software Required:
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.
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');
}
});
// 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.
References:
Date:
Aim:
Software Required:
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.
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.
Result:
The code for Helmet Middlewarein express.js is executed successfully without any errors.
References:
Basics of Typescript
Exp. No.:
Date:
Aim:
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:
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):
TypeScript files typically have a .ts extension. You can create a TypeScript file using a code
editor or IDE of your choice.
Basic Types:
TypeScript introduces static typing through the use of types. Here are some basic types in
TypeScript:
void: Represents the absence of a value (often used for functions that don't return anything).
Variable Declaration:
You can declare variables using let, const, or var as in JavaScript, but TypeScript allows you
to specify the variable's type:
Functions:
You can specify the types of function parameters and return values:
return x + y;
Interfaces:
Interfaces define the structure of objects and classes. They are used to enforce a specific shape
for objects:
interface Person {
name: string;
age: number;
Classes:
TypeScript supports class-based object-oriented programming. You can define classes with
properties and methods:
class Animal {
makeSound() {
Type Annotations:
You can create custom type aliases and use union types to define more complex types:
Enums:
enum Color {
Red,
Green,
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:
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.
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" };
a.html
<!DOCTYPE html>
<html lang="en">
<body>
<script src="9a.js"></script>
</body>
</html>
Result:
The code for Basics of typescriptis executed successfully without any errors.
References:
Function
Exp. No.:
Date:
Aim:
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:
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:
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:
return x - y;
};
Arrow Functions:
You can specify optional parameters by adding a ? after the parameter name, and you can provide
default values for parameters:
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:
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:
} else {
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.
Generic Functions:
TypeScript supports generics, which allow you to write functions that work with different data
types while preserving type safety:
return arg;
Program:
b.ts
price: number;
];
productList.addEventListener("click", handleProductSelection);
void {
// Use arrow function to filter product array by productId const selectedProduct: Product |
undefined = products.find( (product) =>product.productId === productId
);
if (selectedProduct) {
b.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Product Selection</title>
</head>
<body>
<h1>Select a Product</h1>
<ul id="product-list">
</ul>
</body>
</html>
Result:
The code for Functiontypescript is executed successfully without any errors.
References:
Date:
Aim:
Consider that developer needs to declare a function getMobileByVendor which accepts string as
input parameter and returns the list of mobiles
Software Required:
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:
return a + b;
In this example, a and b are parameters of type number, which means the function addNumbers
expects two numbers as input.
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:
return a + b;
If a function doesn't return any value, you can specify its return type as void. For example:
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:
if (greeting) {
} else {
In this example, the greeting parameter is optional, so you can call the greet function with or
without providing a greeting argument.
You can provide default values for parameters by assigning a value after the parameter's type. For
example:
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
];
c.html
<!DOCTYPE html>
<html lang="en">
<body>
<script src="c.js"></script>
</body>
</html>
Result:
The code for Parameter and return types is executed successfully without any errors.
References:
Arrow Function
Exp. No.:
Date:
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 or eq..
Software Required:
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.
return a + b;
};
In this example:
=> is the arrow notation indicating the beginning of the function body.
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:
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.
class Counter {
constructor() {
document.addEventListener("click", () => {
this.count++;
});
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
price: number;
];
});
};
myfunction(250);
9d.html
<!DOCTYPE html>
<html lang="en">
<body>
<script src="9d.js"></script>
</body>
</html>
Result:
The code for Arrow Functionis executed successfully without any errors.
References:
Date:
Aim:
Software Required:
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:
if (greeting) {
} else {
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:
In this example, if you don't provide a greeting argument when calling the greet function, it
will default to "Hello."
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:
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
manufacturer: string;
return filteredMobiles;
constsamsungMobiles = getMobileByManufacturer('Samsung');
console.log(samsungMobiles);
constsamsungMobile101 = getMobileByManufacturer
9e.html
<!DOCTYPE html>
<html lang="en">
<body>
<script src="9e.js"></script>
</body>
</html>
Result:
The code for Optional and Default Parametersin typescriptis executed successfully without any
errors.
References:
Rest Parameter
Exp. No.:
Date:
Aim:
Implement business logic for adding multiple Product values into a cart variable w is type
of string array.
Software Required:
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.
You can also combine rest parameters with other parameters in a function:
In this example, the greet function takes a greeting parameter followed by a rest parameter
names, which captures multiple names passed as arguments.
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
// 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
// Example usage:
10a.html
<!DOCTYPE html>
<html lang="en">
<body>
<script src="10a.js"></script>
</body>
</html>
Result:
The code for Rest Parameters is executed successfully without any errors.
References:
Creating an Interface
Exp. No.:
Date:
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.
Software Required:
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:
interface Person {
firstName: string;
lastName: string;
age: number;
firstName: "John",
lastName: "Doe",
age: 30,
};
console.log(person.age); // Output: 30
In this example:
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;
makeSound() {
console.log(`${this.name} 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.
interface MathOperation {
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.
Program:
10b.ts
// Create a new Product object using the specified values const product: Product = {
productId, productName }; return product;
// Example usage:
10b.html
<!DOCTYPE html>
<html lang="en">
<body>
<script src="10b.js"></script>
</body>
</html>
Result:
The code for Creating an Interface in typescript is executed successfully without any errors.
References:
Duck Typing
Exp. No.:
Date:
Aim:
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.
interface Bird {
fly(): void;
interface Fish {
swim(): void;
if ("fly" in animal) {
animal.fly();
animal.swim();
} else {
fly() {
},
};
swim() {
},
};
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
};
console.log(product);
10c.html
<!DOCTYPE html>
<html lang="en">
<body>
<script src="10c.js"></script>
</body>
</html>
Result:
The code for Duck Typingin typescript is executed successfully without any errors.
References:
Function Types
Exp. No.:
Date:
Aim:
Software Required:
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:
To define a function type, you use a combination of parameter names and types followed by
an arrow (=>) and the return type. For example:
program:
10d.ts
interface Calculator {
};
console.log(add(54, 31));
10d.html
<!DOCTYPE html>
<html lang="en">
<body>
<script src="10d.js"></script>
</body>
</html>
Result:
The code for Function Typesin typescript is executed successfully without any errors.
References:
Extending Interfaces
Exp. No.:
Date:
Aim:
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:
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:
You can extend an interface using the extends keyword. Here's an example:
interface Shape {
color: string;
radius: number;
color: "red",
radius: 5,
};
console.log(myCircle.radius); // Output: 5
program:
11a.ts
interface Category {
id: number;
name: string;
interface Product {
id: number;
name: string;
price: number;
description: string;
id: 1,
price: 10.99,
};
console.log(myProduct);
11a.html
<!DOCTYPE html>
<html lang="en">
<body>
<script src="11a.js"></script>
</body>
</html>
Result:
The code of Function for Typesof Extending interface in typescript is executed successfully
without any errors.
References:
Classes
Exp. No.:
Date:
Aim:
Consider the Mobile Cart applwhich extends properties from two other declared interfaces
like Category.Productlist array.
Software Required:
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.
class Person {
// Properties
firstName: string;
lastName: string;
// Constructor
this.firstName = firstName;
this.lastName = lastName;
// Method
sayHello() {
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.
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.
studentId: number;
this.studentId = studentId;
study() {
console.log(`${this.firstName} is studying.`);
Getters and Setters: TypeScript allows you to define getter and setter methods for class
properties to control access and modification.
class Circle {
constructor(radius: number) {
this._radius = radius;
return this._radius;
if (value >= 0) {
this._radius = value;
} else {
console.log(circle.radius); // Output: 5
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 {
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:
Result:
The code for Classes in typescript is executed successfully without any errors.
References:
Constructor
Exp. No.:
Date:
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>>"
Software Required:
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
this.firstName = firstName;
this.lastName = lastName;
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>
Result:
The code for Constructor in typescript is executed successfully without any errors.
References:
Access Modifiers
Exp. No.:
Date:
Aim:
Software Required:
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 {
this.productId = id;
this.productName = name;
this.productPrice = price;
this.productCategory = category;
return this.productPrice;
11d.html
<!DOCTYPE html>
<html lang="en">
<body>
<script src="11d.js"></script>
</body>
</html>
Result:
The code for Access Modifiersin typescript is executed successfully without any errors.
References:
Exp. No.:
Date:
Aim:
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"]).
const person = {
firstName: "John",
lastName: "Doe",
age: 30,
isStudent: false,
};
console.log(person.age); // Output: 31
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()).
const calculator = {
return a + b;
},
return a - b;
},
};
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;
},
};
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 {
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>
Result:
The code for Properties and Method in typescript is executed successfully without any errors.
References:
_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)
Date:
Aim:
Software Required:
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.
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 {
console.log(`Hello, ${name}!`);
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
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 {
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 {
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
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
productlist.ts
// Import the Product class as a global variable declare const Product: any;
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>
<script>
document.getElementById('productId').textContent = product2.getProductId().toString();
</script>
</body>
</html>
Result:
The code for Creating and using Namespacein typescript is executed successfully without any errors.
References:
Date:
Aim:
Software Required:
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 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.
module MyModule {
console.log(`Hello, ${name}!`);
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
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.
To define an external module, create a separate TypeScript file (e.g., myModule.ts) that
contains your module's code.
// myModule.ts
console.log(`Hello, ${name}!`);
You can import items from an external module using the import statement.
from "./myModule";
console.log(variable1); // Output: 10
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
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 {
12c.html
<!DOCTYPE html>
<html>
<head>
<title>Mobile Cart</title>
<meta charset="utf-8">
</head>
<body>
<h1>Mobile Cart</h1>
<form>
<label for="quantity">Quantity:</label>
<label for="price">Price:</label>
</form>
<div>
</div>
<script src="mobile-cart.js"></script>
<script>
function calculateTotalPrice() {
constquantityInput = document.getElementById("quantity");
constpriceInput = document.getElementById("price");
consttotalPriceInput = document.getElementById("totalPrice");
totalPriceInput.value = totalPrice.toFixed(2);
</script>
</body>
</html>
Result:
The code for Creating and using Modulesin typescript is executed successfully without any errors.
References:
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:
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.
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.
return value;
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.
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;
return obj.length;
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
12d.html
<!DOCTYPE html>
<html>
<head>
<script src="12d.js"></script>
</head><body><script>
</script>
</body>
</html>
Result:
The code for Generic functions, typesin typescript is executed successfully without any errors.
References: