Final - PPT 2
Final - PPT 2
1a Case-insensitivity,Platform-independency
DOCTYPE Declaration, Types of Elements
HTML Elements - Attributes, Metadata Element
1b Sectioning Elements
1c Paragraph Element, Division and Span
Elements, List Element
1d Link Element
1e Character Entities
1f HTML5 Global Attributes
2a Creating Table Elements, Table Elements :
Colspan/Rowspan Attributes, border, cellspacing,
cellpadding attributes Enhance the details
page of IEKart's Shopping application by
adding a table element to display the available
mobile/any inventories.
2b Creating Form Elements, Color and Date Pickers,
Select and Datalist Elements
2c Input Elements - Attributes
2d Media, Iframe
3a Type of Identifiers
3b Primitive and Non Primitive Data Types
3c Operators and Types of Operators
3d Types of Statements, Non - Conditional
Statements, Types of Conditional Statements,
if Statements,switch Statements
4a Types of Loops
Types of Functions, Declaring and Invoking
Function, Arrow Function, Function Parameters,
Nested Function, Built-in Functions, Variable
Scope in Functions
4b Working With Classes, Creating and
Inheriting Classes
4c In-built Events and Handlers
4d Working with Objects, Types of Objects,
Creating Objects, Combining and cloning
Objects using Spread operator, Destructuring
Objects, Browser Object Model, Document
Object Mode
5a Creating Arrays, Destructuring Arrays,
Accessing Arrays, Array Methods
5b Introduction to Asynchronous Programming,
Callbacks, Promises, Async and Await,
Executing Network Requests using Fetch API
5c Creating Modules, Consuming Modules
6a How to use Node.js
6b Create a web server in Node.js
6c Modular programming in Node.js
6d Restarting Node Application
6e File Operations
7a Defining a route, Handling Routes, Route
Parameters, Query Parameters
7b How Middleware works, Chaining of
Middlewares, Types of Middlewares
7c Connecting to MongoDB with Mongoose,
Validation Types and Defaults
7d Models
8a CRUD Operations
8b API Development
8c Why Session management, Cookies
8d Sessions
8e Why and What Security, Helmet Middleware
9a Basics of TypeScript
9b Function
9c Parameter Types and Return Types
9d Arrow Function
9e Optional and Default Parameters
10a Rest Parameter
10b Creating an Interface
10c Duck Typing
10d Function Types
11a Extending Interfaces
11b Classes
11c Constructor
11d Access Modifiers
12a Properties and Methods
12b Creating and using Namespace
12c Creating and using Modules
12d What is Generics, What are Type Parameters,
Generic Functions, Generic Constraints
Hyper Text Markup Language (HTML) is a standard markup language to create the
structure of a web page. It annotates the content on a web page using HTML elements.
In a web page, all instructions to the browser are given in the form of HTML tags, also known as
HTML elements.
The basic structure of html is:
<!DOCTYPE html>
<html>
<head>
<title> Homepage </title>
</head>
<body>
//paragraph
</body>
</html>
Case-insensitivity :
HTML elements are case-insensitive. The browser understands the
HTML tags irrespective of their cases.
Syntax:
<!DOCTYPE html>
<html>
<head>
<title>Homepage </title> </head>
<body> Hello
World!
</boDy>
</html>
Syntax:
<!DOCTYPE html>
<html>
<head>
<title>sample page</title>
</head>
<body>
<p>Hello World!</p>
</body> </html>
Output:
Doctype Declaration :
There are many versions of HTML out there such as HTML 2.0, HTML 3.0, HTML 3.2,
HTML4.0, HTML 4.01 and latest is HTML5.0. In each version, some elements and attributes are
either added or depreciated. The appearance of your .html page depends on how the browser
renders HTML elements. And how the browser renders HTML elements depends on how the
Types of Elements:
HTML elements can be further categorized into two as below: Block Element:
A block element begins on a new line occupying the entire width of the parent tag.
Inline Element: An inline element occupies the necessary space to accommodate the content in the
element. Inline elements can be nested within other inline elements, whereas, block elements
cannot be nested within inline elements.
Html Elements-Attributes, metadata elements:
HTML elements can contain attributes that can be considered as an additional feature to set
various properties and they are optional. Some of the attributes can be used with any of the HTML
elements and there can be referred to as ‘global attributes’. Also, some attributes can be used only
with particular elements. Following are some features of attributes:
The lang attribute specifies the language of the content of the HTML page.
Metadata:
The <meta> tag defines metadata about an HTML document. Metadata is data (information) about
data.
<meta> tags always go inside the <head> element, and are typically used to specify character set,
page description, keywords, author of the document, and viewport settings.
Syntax:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Syntax:
<h1>Courses offered:</h1>
<ol>
<li>HTML5</li>
<li>CSS</li>
<li>JS</li>
<li>Bootstrap</li>
</ol>
HTML Description list is also a list style which is supported by HTML and XHTML. It is also
known as definition list where entries are listed like a dictionary or encyclopedia.
Syntax:
<dl>
<dt> Description Term 1 </dt>
<dd> Description Definition 1 </dd>
<dt> Description Term 2 </dt>
<dd> Description Definition 2 </dd> </dl>
1d) Link Element:
A website necessarily is a collection of related web pages, where each web page is typically
created for a particular purpose.
When developing any website:
● Each web page is necessarily coded in individual HTML files.
● To see a particular web page, the respective HTML file has to be opened up in a browser.
Below are the advantages if hyperlinks are used:
● We can create connections or links between HTML documents/web
pages and users can navigate from one web page to another by clicking on "hyperlinks".
● We would now feel that we have a website which is a collection of interconnected web
pages.
Link elements are defined using <a> .. </a> tag as below:
A hyperlink is a prime way in which users can navigate from one web page to another. A
hyperlink can point to another web page, or website, or files, or even specific locations on the
same web page.Hyperlinks can be of any of the below types:
Text hyperlink:
● A clickable text is used to take the user to another web page.Largely, we use text-based
hyperlinks.
● This text usually appears with an underline and in a different color.
● This color mapping is automatically done by the browser for all text hyperlinks.
Syntax:
<a href="Enquire.html"> Click here to connect to us </a><br/>
Image hyperlink:
● A clickable image is used to take the user to another web page.
Syntax:
<a href="http://www.google.com">
<img src="google.jpg" />
</a>
Bookmark hyperlink:
When a web page is lengthy, we commonly come across icons or links that say "Go to Top" or
"Go to Bottom". Click on these links does take the user to the top of the page or bottom, as
applicable. Sometimes we also observe, on click of a text in the menu bar, the page auto scrolls to
that particular section on that page. This is achieved by using the Bookmarking concept and the
same is implemented by using hyperlinks.
Syntax:
<h2 id="top">Topic</h2>
<p>Detail……</p>
<p>Detail……</p>
<p>Detail……</p>
<a href="#top">Go to Top</a>
Email hyperlink:
● It allows users to send an email by clicking on that link.
Syntax:
<a href="mailto:[email protected]?Subject=Hello%20again">Sen d Mail</a>
Contact number hyperlink:
● It allows the user to call a number by clicking on that link.
Let us discuss various hyperlinks that can be created in an HTML page.
Syntax:
<a href="tel:+9999">Call Us</a>
The table below lists widely used character entities supported in HTML5.
 
Non-breaking space
< Less than < <
> Greater than > >
& Ampersand & &
© Copyright © ©
€ Euro &euro €
Attribute Description
contenteditable Allows the user to edit content. Possible values are true/false.
dir Specifies text direction. Possible values are Itr/ rtl.
title Displays the string message as a tooltip.
Specifies whether the spelling of an element's value should be checked
spellcheck
or not. Possible values are true/false.
id Gives a unique id to an element.
EXPERIMENT-2
COURSE NAME: JAVASCRIPT
A. CREATING TABLE ELEMENTS
HTML Tables provide a means by which we can create a tabular format
of data on the web.
1.The table element is defined in HTML using <table>...</table> tag It contains
table header and table body.
2.The table header is for adding header information like column headers and the
table body is for table contents.
The <caption> tag defines a table caption.The <caption> tag must be inserted
immediately after the <table> tag.
The row span attribute accepts a numeric value and merges specified
numeric value of rows together.
Rowspan Syntax:
HTML tables can adjust the padding inside the cells, and also
the space between the cells.
Example
th , td {
padding: 15px;
}
HTML Forms:
An HTML form is used to collect user input. The user input is most often
sent to a server for processing.
The form can be created using <form>...</form> tag of HTML.
• method: Defaults to HTTP "get" method of submission to the
server. To use HTTP "post", use method="post"
• action: The URL to which the form data has to be submitted
• target: Specifies if the submitted result will open in the current
window, a new tab, or on a new frame
The form input element is used to collect details from the user.
Input type - text:
A single-line text field. The value attribute defines the value of the input
field. Name: <input type="text" value="">
<select> element :
• Defines a drop-down list.
Ex:
Country code: <select >
<option value="">-- Please choose a country code --</option>
<option value="+213">+213</option>
<option value="+91">+91</option>
<option value="+244">+244</option>
<option value="+61">+61</option>
<option value="+973">+973</option>
</select>
<datalist> element:
• Defines a set of pre-defined options available to choose for an
<input> element.
Ex:
Country: <input list="countries">
<datalist id="countries">
<option value="India">
<option value="France">
<option value="Singapore">
<option value="Thailand">
<option value="United Arab Emirates">
<option value="United States of America">
</datalist>
Pattern:
The pattern attribute creates a custom pattern validator.
Multiple:
The multiple attribute value allows the user to enter/select/upload more
than one value.
Required:
The required attribute specifies that user input is a must.
.
Media
The media attribute specifies what media/device the linked
document is optimized for.
This attribute is used to specify that the target URL is designed for
special devices (like iPhone) , speech or print med
Audio Element:
Embedding audio to a web page can be done with <audio>...</audio>
tag. The <audio> tag has an attribute 'src' which defines the
location of the audio file. It also has an attribute 'controls' which
specifies whether to display the player controls.
iframe:
We might have requirements to include documents, videos, interactive
videos, or even other web content into a web page directly from
external sources
.It is defined using <iframe>…</iframe> tag.
EXPERIMENT-3
COURSE NAME: JAVASCRIPT
A. TYPES OF IDENTIFIERS:
JavaScript identifiers are the name that we give to variables, objects,
functions, arrays, classes, etc. We must use a unique name so as to identify them.
We then use the identifier to refer to the variable, functions, etc elsewhere in the
program. There are certain rules & restrictions that we must follow when we name
an identifier.
Here are the main types of identifiers in JavaScript:
1. Variables:
Used to store data values.
Example: ‘let myVariable=10’;
2. Constants:
Similar to variables, bute their values cannot be reassigned.
Example: ’const PI=3.14’;
3. Functions:
Used to define reusable blocks of code.
Example: ’function myFunction() {/*code*/}’
4. Classes:
Used to create objects with shared properties and methods.
Example: ‘class Dog{/*code*/}’
5. Interfaces:
Used in the context of object-oriented programming to define the
structure that classes must adhere to.
Example: ‘interface Shape {/*code*/}’
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
Bitwise Operators
Type Operators
Any numeric operand in the operation is converted into a 32 bit it number. The
result is converted back to a JavaScript number.
D. TYPES OF STATEMENTS:
There are two types of statements in JavaScript. They are:
1. Non-conditional Statements.
2. Conditional Statements.
1. Non-Conditional Statements:
Non-conditional statements in JavaScript are statements that do not
involve conditional logic, such as if, else, switch, etc. These statements
are executed regardless of any condition being met. Some common
non-conditional statements in JavaScript include:
o Declaration Statements:
-Variable declaration (‘var’, ’let’, ’const’
-Function declaration(‘function’)
o Loop Statements:
- ‘for’ loop
- ‘while’ loop
- ‘do…while’ loop
- ‘for…in’ loop
- ‘for…of’ loop
o Control Flow Statements:
- ‘break’
- ‘continue’
- ‘return
2.Conditional Statements:
Conditional Statements in JavaScript allow you to execute specific
blocks of code based on conditions. If the condition meets then a particular block of
action will be executed otherwise it will execute another block of action that
satisfies that particular condition.
There are several methods that can be used to perform Conditional Statements in
JavaScript.
o If Statement
o If-else Statement
o Else if statement
o Switch Statement
o Ternary Statement
JavaScript if Statement
The if statement is used to evaluate a particular condition. If the condition
holds true, the associated code block is executed.
Syntax:
JavaScript if-else Statement
The if-else statement will perform some action for a specific condition. Here
we are using the else statement in which the else statement is written after the if
statement and it has no condition in their code block.
Syntax:
E. TYPES OF LOOPS:
JavaScript Loops are powerful tools for performing repetitive tasks
efficiently. Loops in JavaScript execute a block of code again and again while the
condition is true.
There are different types of loops in JavaScript:
for Loop
while Loop
do-while Loop
Break Statement
Continue Statement
Infinite Loop (Loop Error)
SYNTAX
Function declaration Example
FUNCTION INVOCATION
The code written inside the function body will be executed only when it is invoked or called.
Example
ANONYMOUS
FUNCTION
• In JavaScript, functions are first-class objects. This means, that you can assign a function as a
value to a variable. For example.
• Here, a function without a name is called an anonymous function which is assigned to a variable
say Hello.
ARROW FUNCTION
• JavaScript has introduced a new and concise way of writing functions using arrow notation. The
arrow function is one of the easiest ways to declare an anonymous function .
• This means that the value of this inside an arrow function is determined by where the
arrow function is written, not where it is called.
• For normal function the value of this depends upon which object is calling the function
• But for arrow function it does not depend on which is calling the function.
• For arrow function it depends on its outer context(global context)
• The global context in JavaScript refers to the outermost scope or environment where
JavaScript code is executed. It represents the highest level of scope in a JavaScript
program and includes variables, functions, and objects that are accessible throughout the
entire program.
FUNCTION PARAMETERS
• Function parameters are the variables that are defined in the function definition and the values
passed to the function when it is invoked are called arguments.
• In JavaScript, function definition does not have any data type specified for the parameters, and
type checking is not performed on the arguments passed to the function.
• JavaScript does not throw any error if the number of arguments passed during a function
invocation doesn’t match with the number of parameters listed during the function definition. If
the number of parameters is more than the number of arguments, then the parameters that have no
corresponding arguments are set to undefined
DEFAULT PARAMETERS
JavaScript introduces an option to assign default values in functions
In the above example, when the function is invoked with two parameters, the default value of
num2 will be overridden and considered when the value is omitted while calling.
REST PARAMETERS
• Rest parameter syntax allows to hold an indefinite number of arguments in the form of an
array
• The rest of the parameters can be included in the function definition by using three dots
( … ) followed by the name of the array that will hold them.
• The rest parameter should always be the last parameter in the function definition
Syntax
Example
In the above example, the first two array elements ‘Andrew’ and 'James’ have been destructured into
individual function parameters arg1 and arg2
NESTED FUNCTIONS
• In JavaScript, it is perfectly normal to have functions inside functions. The function within another
function body is called a nested function.
• The nested function is private to the container function and cannot be invoked from outside the
container function.
BUILT IN FUNCTIONS
• JavaScript comes with certain built-in functions. To use them, they need to be invoked.
VARIABLE SCOPE
• Variable declaration in the JavaScript program can be done within the function or outside the
function. But the accessibility of the variable to other parts of the same program is decided based
on the place of its declaration. This accessibility of a variable is referred to as scope.
• JavaScript scopes can be of three types:
• Global scope
• Local scope
• Block scope
GLOBAL SCOPE
• Variables defined outside function have Global Scope and they are accessible anywhere in the
program.
LOCAL SCOPE
• Variables declared inside the function would have local scope. These variables cannot be accessed
outside the declared function block
Block Scope
• In 2015, JavaScript introduced two new keywords to declare variables: let and const.
• Variables declared with 'var' keyword are function-scoped whereas variables declared with 'let' and
'const' are block-scoped and they exist only in the block in which they are defined
• In the above example, the variable flag declared inside 'if' block is accessible outside the block
since it has function scope
• Modifying the code to use 'let' variable will result in an error:
• The usage of 'let' in the above code snippet has restricted the variable scope only to 'if' block.
• 'const' has the same scope as that of 'let' i.e., block scope.
INHERITANCE CLASSES
• In JavaScript, one class can inherit another class using the extends keyword. The subclass inherits
all the methods ( both static and non-static ) of the parent class.
• Inheritance enables the reusability and extensibility of a given class.
• JavaScript uses prototypal inheritance which is quite complex and unreadable. But, now you
have 'extends' keyword which makes it easy to inherit the existing classes.
• Keyword super can be used to refer to base class methods/constructors from a subclass
Syntax:
EXCEPTION HANDLING
• Exception handling is accomplished with a try...catch statement. When the program encounters an
exception, the program will terminate in an unfriendly manner. To protect against this, the code
can be placed in a try...catch statement and avoid terminating the program unexpectedly.
• Try statements: It lets the developer validate a block of code whether it will result in some errors
or not.
• Catch statements: It lets the developer handle the error without terminating the program in an
unfriendly manner.
• Throw statements: It helps the developer to create custom errors.
• Finally statements: It lets the developer execute code, after the try and catch block
execution, irrespective of the result
TYPES OF OBJECTS
CREATING OBJECTS
• In JavaScript objects, the state and behaviour is represented as a collection of properties
• Each property is a [key-value] pair where the key is a string and the value can be any JavaScript
primitive type value, an object, or even a function.
• JavaScript objects can be created using two different approaches
Syntax:
CREATING OBJECTS USING FUNCTION CONSTRUCTOR
• Constructor functions are used to create multiple instances of objects with the same structure and
behavior.
• They define a blueprint for creating objects by using a function as a template.
• Constructor functions use the new keyword to create new instances of objects based on the defined
blueprint.
• Here's an example of creating an object using a constructor function:
DESTRUCTING OBJECTS
Destructuring objects in JavaScript allows you to extract multiple properties from an object and
assign them to variables in a concise and readable way. It's a powerful feature introduced in
ECMAScript 6 (ES6) that simplifies working with objects.
In the below example an object is destructured into individual variables:
OBJECT DESTRUCTURING IN FUNCTIONS
The property 'country' of the object has been destructured and captured as a function parameter.
BUILT IN OBJECTS
• The Global object allows to declare variables and functions that can be accessed anywhere.
Date
String
Math
RegEx
JSON
To access an element in the HTML page, following methods can be used on the
'document' object from DOM.
getElementById(x)
getElementsByTagName(x)
getElementsByClassName()
querySelectorAll()
InnerHeight: This property holds the inner height of the window’s content area.
InnerWidth: This property holds the inner width of the window’s content area
OuterHeight: This property holds the outer height of the window including toolbars and scrollbars.
OuterWidth: This property holds the outer width of the window including toolbars and scrollbars.
LocalStorage: This property allows access to object that stores data without any expiration date
SessionStorage: This property allows access to objects that store data valid only for the current
session.
Methods
open() method, opens a new window. Usage: window.open ("http://www.xyz.com");
close() method, closes the current window. Usage: window.close();
If required, BOM also gives a specific object to target only one of the window properties. For
example, if the concern is about the list of URLs that have been visited by the user and there is no
need for any other information about the browser, BOM gives the 'history' object for this. It
provides programmatic navigation to one of the URLs previously visited by the user. Following
are the properties or methods that helps in doing so.
Property:
length returns the number of elements in the History list. Usage: history.length;
Methods:
back() method, loads previous URL from history list. Usage: history.back();
forward() method, loads next URL from history list. Usage: history.forward();
go() method, loads previous URL present at the given number from the history list.
It contains information about the client, that is, the browser on which the web page is
rendered. The following properties and methods help in getting this information.
These nodes appear in a hierarchical structure inside the browser. And this
hierarchical relationship between the nodes allows us to traverse through the
DOM tree.
The top node is called the root. It does not have any parents.
Every other node in the tree belongs to one parent.
Every node may have several children.
Nodes with the same parent are referred to as siblings.
parentNode: Returns a Node object that is the parent node of the specified node. This
property can be retrieved and cannot set it.
childNodes: Returns NodeList object, i.e collection of child nodes of the specified node.
Each child can be accessed by an index number that refers to its position inside the parent
element. The first position is at index '0'.
firstChild: Returns Node object which is the first child of the specified node. Its is
equivalent to childNodes[0].
lastChild: Returns Node object which is the last child of the specified node.
nextSibling: Returns the Node object of the node that immediately follows the specified
node at the same tree level.
previousSibling: Returns the Node object of the node that the previous node of the
specified node at the same tree level.
Experiment – 5
Arrays, Asynchronous Programming, Modules in JavaScript
Arrays in JavaScript:
In JavaScript, an array is a special type of object used to store multiple values in a single
variable.
Arrays can hold different types of data, including numbers, strings, objects, and even other
arrays.
We can access the values of arrays by referring to an index number.
Syntax of array:
const array_name = [item1, item2, ...];
Creating arrays:
You can create an array using square brackets [] and separating each element with a comma.
Creating an empty array:
let myArray = [];
Creating an array with elements:
let fruits = ['apple', 'banana', 'orange'];
Modifying Elements:
You can modify elements in an array by accessing them using their index and assigning a new
value.
fruits[1] = 'kiwi';
console.log(fruits); // Outputs: ["apple", "kiwi", "orange"]
Array Methods:
JavaScript provides a variety of methods to manipulate arrays:
let fruits = ['apple', ‘kiwi', 'orange'];
Push:
push() adds elements to the end of an array.
fruits.push('grape');
console.log(fruits); // Outputs: ["apple", "kiwi", "orange", "grape"]
Pop:
pop() removes the last element of an array.
let lastFruit = fruits.pop();
console.log(lastFruit); // Outputs: "grape"
console.log(fruits); // Outputs: ["apple", "kiwi", "orange"]
Unshift:
Unshift() adds elements to the beginning of an array.
let fruits = ['apple', ‘kiwi', 'orange'];
fruits.unshift('grape');
console.log(fruits); // Outputs: ["grape", "apple", "kiwi", "orange"]
Shift:
Shift() removes the first element.
let firstFruit = fruits.shift();
console.log(firstFruit); // Outputs: "grape"
console.log(fruits); // Outputs: ["apple", "kiwi", "orange"]
Slice:
slice() method extracts a section of an array and returns a new array.
let fruits = ['apple', ‘kiwi', 'orange'];
let citrus = fruits.slice(1, 3);
console.log(citrus); // Outputs: ["kiwi", "orange"]
Concat:
concat() method is used to merge two or more arrays. It does not modify the existing arrays but
instead returns a new array.
let moreFruits = ['grapefruit', 'cherry'];
let allFruits = fruits.concat(moreFruits);
console.log(allFruits); // Outputs: ["apple", "kiwi", "orange", "grapefruit", "cherry"]
Array Destructuring :
Array destructuring in JavaScript allows you to extract values from arrays and assign them
to variables in a concise and convenient way. It's a handy feature introduced in ECMAScript 6
(ES6) that simplifies working with arrays.
Example:
let colors = ['red', 'green', 'blue'];
// Destructuring assignment
let [firstColor, secondColor, thirdColor] = colors;
console.log(firstColor); // Outputs: "red"
console.log(secondColor); // Outputs: "green"
console.log(thirdColor); // Outputs: "blue"
Skipping Elements:
You can skip elements in the array by leaving placeholders (commas) for them.
let colors = ['red', 'green', 'blue'];
let [first, , third] = colors;
console.log(first); // Outputs: "red"
console.log(third); // Outputs: "blue"
Using Rest Syntax:
You can use the rest syntax (...) to capture remaining elements into a new array.
let [head, ...tail] = colors;
console.log(head); // Outputs: "red"
console.log(tail); // Outputs: ["green", "blue"]
Default Values:
You can provide default values for variables in case the array doesn't have enough elements.
let [color1, color2, color3, color4 = 'yellow'] = colors;
console.log(color1); // Outputs: "red"
console.log(color2); // Outputs: "green"
console.log(color3); // Outputs: "blue"
console.log(color4); // Outputs: "yellow"
Asynchronous programming:
Asynchronous programming in JavaScript allows you to execute code non-sequentially,
meaning that certain operations can be started without having to wait for other operations to
complete. This is particularly useful for tasks like making network requests, reading files, or
executing long-running computations without blocking the execution of other code.
JavaScript supports asynchronous programming through various mechanisms:
Callbacks
Promises
async/await syntax.
Callbacks in java Script:
Callbacks in JavaScript are functions passed as arguments to other functions, which are
then invoked or "called back" at a later time, usually after some asynchronous operation has
completed. Callbacks are a fundamental concept in JavaScript, especially when dealing with
asynchronous code. They allow you to control the flow of execution and handle the result of an
asynchronous operation once it's finished.
Fetch data using Callbacks:
function fetchData(callback) {
// Simulating an asynchronous operation
setTimeout(() => {
const data = 'Data fetched successfully';
// Call the callback function with the data
callback(data);
}, 1000);
}
// Define a callback function
function processResult(result) {
console.log(result);
}
// Call the function and pass the callback
fetchData(processResult);
Promises:
Promise is a way to handle Asynchronous operations. A promise is an object that
represents a result of operation that will be returned at some point in the future.
Promise States:
A promise will be in any one of the three states:
Pending: Neither fulfilled nor rejected
Fulfilled: Operation completed successfully
Rejected: Operation failed.
JavaScript Modules:
JavaScript, like most programming languages, was initially used for small tasks. But as its
popularity grew, so did the amount of code that needed to be written. Having a large amount of
code in a single file can be problematic, so it's helpful to split the code into multiple parts. This is
where modules come in handy.
JavaScript modules are a way to organize and structure code. They allow developers to
break their code into smaller, reusable pieces. You can think about them as smaller pieces of code
that you can import and export between different parts of an application.
Benefits of using Modules:
More Organized Code
Code Reusability
No Naming Conflicts
To use modules, we need to import them in our code. The code must be exported to import it
in other files.
Types of File Exports in JavaScript:
• Default export
• Named export
Default export:
Example:
const sum = (a, b) =>{
return a + b;
}
Export default sum;
Named export:
const sum = (a, b) =>{
return a + b;
}
const sub = (a, b) =>{
return a - b;
}
export {sum, sub};
Importing Modules:
import a single default export
import sum from “calc.js”
import a single named export
import {sum} from “calc.js”
import multiple named exports
import {sum, sub} from “calc.js”
import an entire module
import * as calc from “calc.js”
calc.sum(2,3);
calc.sub(10,5);
Using import aliases in Javascript:
Import aliases are where you take your standard import, but instead of using a pre-defined name
by the exporting module, you use a name that is defined in the importing module.
Syntax:
For named exports:
export {Something1, Something2}
import {Something1 as MySomething} from "my-module.js"
For default exports:
export default Something
import MySomething from "my-module.js"
EXPERIMENT – 6
Node.js
a) Module Name: How to use Node.js.
Verify how to execute different functions successfully in the Node.js platform.
b) Module Name: Create a web server in Node.js
Write a program to show the workflow of JavaScript code executable by creating web server in
Node.js.
c) Module Name: Modular programming in Node.js
Write a Node.js module to show the workflow of Modularization of Node application.
d) Module Name: Restarting Node Application
Write a program to show the workflow of restarting a Node application.
e) Module Name: File Operations
Create a text file src.txt and add the following data to it. Mongo, Express, Angular, Node.
Install Node.js: First, you need to download and install Node.js from the official website
(https://nodejs.org).
Write Your JavaScript Code: Create a JavaScript file (e.g., app.js) where you'll write your
Node.js code.
Write Your Node.js Code: In your JavaScript file (app.js), you can write server-side code
using Node.js APIs.
Run Your Node.js Application: You can run your Node.js application by navigating to its
directory in the terminal and running node app.js.
Functions
In Node.js, functions work similarly to functions in JavaScript in the browser, with some
additional capabilities and considerations for server-side programming.
To use a function, it must be defined or declared and then it can be invoked anywhere in
the program.
A function declaration also called a function definition, consists of the function keyword,
followed by: function name
A list of parameters to the function separated by commas and enclosed in parentheses, if
any.
A set of statements that define the function, also called a function body, enclosed in curly
brackets { }
Syntax:
Function Declaration:
Example:
Function Invoking:
The code written inside the function body will be executed only when it is invoked or called.
Syntax:
Example:
3. Asynchronous Functions: Node.js is particularly known for its support for asynchronous
programming. Functions can be defined to execute asynchronously using callbacks,
Promises, or the async /await syntax.
The example of a web server written in Node.js using the built-in http module:
Steps to save and run the code
Save this code in a file, for example server.js. Then, you can run this script using Node.js
by executing node server in your terminal or command prompt. This will start a web
server listening on http://127.0.0.1:3000/
You can visit http://127.0.0.1:3000/ in your web browser, and you should see the message
"Hello, World!" displayed in the browser window.
Modular Programming
Modular programming in Node.js involves breaking down your code into separate modules or
files, each responsible for a specific functionality or feature . This approach promotes code
organization, reusability, and maintainability.
rectangle.js:
Output:
16
50.24
Explanation of Code:
In the above example : rectangle.js and circle.js contain functions to calculate the area of a
rectangle and a circle, respectively. They export these functions using module.exports.
app.js is the main file that imports the modules rectangle and circle. It then uses the
functions exported by these modules to calculate and print the areas of a rectangle and a
circle.
To run this program, ensure all files are in the same directory, and then execute node
app.js in the terminal. This will output the calculated areas of the rectangle and the circle.
This modular approach makes it easier to manage code as the application grows. Each
module can focus on a specific task, making the codebase more organized and easier to
maintain.
• Create a package.json file with a script to start your application using nodemon.
• Save the changes and run the node application by entering this command in command
prompt.
• Now, whenever you make changes to your app.js file and save it, nodemon will
automatically restart the Node.js application.
• Now the node application runs and the terminal shows following output.
• Make changes to code in app.js. The application will restart automatically and the
following will be output in terminal.
• Then the changes will be made and reload the server in the browser. And changes will be
displayed.
File Operations
• In Node.js, file operations are crucial for interacting with the file system, allowing
developers to read, write, and manipulate files.
• The built-in fs module is the primary module used for file operations.
• These built-in modules are used to perform various operations like reading file, writing to
file, existence of file, renaming the file, appending data to file, deleting file, etc.
Writing to File
The fs.writeFile() function is used to asynchronously write data to a file. If the file already exists,
it will be truncated.
Syntax:
Example:
Output:
File has been written.
Reading a File
Syntax:
Example:
Output:
File content: Mongo, Express, Angular, Node.
Appending a File
Syntax:
Example:
Output:
Content has been appended.
Rename a File
Syntax:
Example:
Output:
File has been renamed.
Delete a File
Syntax:
Example:
Output:
File deleted successfully.
Existence of a File
Syntax:
Example:
Output:
File does not exist.
EXPERIMENT - 7
Expess.js
Introduction to Express: Express is a layer built on the top of the Node.js that helps manage server
and routes.
-Node.js does not support request handling, HTTP methods so, this is where Express.js comes into
picture.
-It also provides a robust set of features to develop applications(web and mobile).
-It is easy to learn, fast, free, flexible and unopinionated ( There isn’t a best way to do something, what
you do is the best way)
-Express makes debugging easier as it identifies the exact part where bugs are.
Advantages of ExpressJS:
1. Express is very easy we can customize and use it as per our needs.
2. A single language JavaScript is used for both front-end and back-end development.
Dis-Advantages of ExpressJS:
Step 2- Now, open your visual studio code, open a new terminal and install npm (node package
manager)
Step 3- After installing npm, you must check the version of npm(Command: npm -v)
Step 4- Create folder(that stores your express file) and open it in visual stdio
Version: 1.0.0
Click enter..
Step 7- Now you will finally install express js for that write command: npm install express
const app=express();
app.get('/',(req,res)=>{
res.send("Welcome to JNTN");
})
app.listen(4000,()=>{
})
Step 9- Open the terminal, go to the main folder write ‘cd <<folder name>>’, press enter,
and then write the command to run the code: node app.js.
Step 10- Now open chrome and go to local host: 4000 to see the result.
Route:
Routers():
Defining routes like above is very tedious to maintain. To separate the routes from our
main index.js file, we will use Express.Route
Route methods:(Examples)
// GET method route
app.get('/', (req, res) => {
res.send('GET request to the homepage')
})
Route paths:(Examples)
//Route path is “/random.text”
app.get('/random.text', (req, res) => {
res.send('random.text')
})
An adventure trails application is a web application, built with Express.js could be a platform
for users to discover, explore, and share information about outdoor trails for activities such as
hiking, biking, or running.
Index.js file:
app.use('/trail', route1);
app.listen(4000,()=>{
})
routes/route.js file:
// Sample trails data (replace this with your actual data source)
const trails = [
];
res.send('Welcome to AdventureTrails!');
// Example: res.render('index');
});
res.send(trails);
});
if (trail) {
res.json(trail);
});
// Other routes for creating, updating, and deleting trails can be added here
module.exports = router;
Output:
Middleware
What's middleware?
These middleware functions have access to response obj (res), request object(req) and next in the
application req-res cycle.
It is used for--
next();
});
Types of Middleware --
1. Application level middleware – For any route this middleware function works.
next();
});
2. Router level middleware – when a route is activated then only these middlewares will work.
Here we can use multiple middlewares.
next();
},
console.log(“Second”);
next();
});
The POST request is handled in Express using the Post express method. This is used when
there is a requirement of fetching data from the client such as form data. The data sent
through the POST request is stored in the request object
Express requires an additional middleware module to extract incoming data of a POST request.
This middleware is called the “body-parser”. We need to install it and configure it with Express
instance.
You can install body-parser using the following command: npm install body-parser
You need to import this package into your project and tell Express to use this as
middleware. (use postman extension to give input data and view the result—by installing
postman extension in visual stdio)
Source code:
app.use(bodyParser.json())
res.send('Hello World!')
})
})
app.listen(3000, () => {
})
Choose the HTTP method as "POST" from the dropdown menu.Enter the URL of your Express.js
server. For example, if your server is running locally on port 3000, the URL would be
http://localhost:3000/submit.
Optionally, you can add headers, query parameters, or authentication if your server requires them
Add request body: Switch to the "Body" tab in Postman.
Select the "raw" option.
Choose JSON format from the dropdown menu.
Enter some sample data in JSON format. For example:
Click on the "Send" button to send the POST request to your Express.js server. Once the request is
sent, you should see the response from your server (localhost: 3000).
Errors in express.js :
In Express.js, errors can occur for various reasons during the execution of your
application. some common types of errors you might encounter are :
“Syntax Errors, Runtime Errors, Database Errors, Custom Errors.”
(II). Custom Errors:
Custom errors are errors that you define yourself to handle specific
scenarios in your application.
res.status(errStatus).json({
success: false,
status: errStatus,
message: errMsg,
stack: process.env.NODE_ENV === 'development' ? err.stack : {}
})
}
app.use(ErrorHandler)
app.use(“/books”,(req,res,next) => {
try{
// code block to be executed
}catch(err){
next(err);
}
})
Error Response(output):
"success": false,
"status": 500,
"message": "Something went wrong",
"stack": "Error: Custom error message\n at app.get
(/path/to/your/app.js:10:15)\n at Layer.handle [as handle_request]
(/path/to/node_modules/express/lib/router/layer.js:95:5)\n at next
(/path/to/node_modules/express/lib/router/route.js:137:13)\n at
Route.dispatch (/path/to/node_modules/express/lib/router/route.js:112:3)\n
at Layer.handle [as handle_request]
(/path/to/node_modules/express/lib/router/layer.js:95:5)\n at
/path/to/node_modules/express/lib/router/index.js:281:22\n at
Function.process_params
(/path/to/node_modules/express/lib/router/index.js:335:12)\n at next
(/path/to/node_modules/express/lib/router/index.js:275:10)\n at
Function.handle (/path/to/node_modules/express/lib/router/index.js:174:3)\n
at router (/path/to/node_modules/express/lib/router/index.js:47:12)"
}
Logging is an essential part of software development and maintenance for several reasons:
“Debugging and Troubleshooting, Monitoring and Performance Analysis,
Security Analysis”.
There are various logging libraries available for Node.js and Express.js, such as
“morgan, winston, and bunyan”.
1. Install morgan:
If you haven't already installed morgan, you can do so using npm: npm install morgan
app.use(morgan('dev'));
// Your routes and other middleware here...
// Start the server
app.listen(port, () => {
});
If you use the provided logging setup in your Express.js application, the output will be
displayed in the console where your application is running. Here's what the output might
look like:
Custom Logging:
If you need more customized logging or want to log additional information, you can create
custom middleware to handle logging.
Code:
});
2022-04-08T12:30:45.678Z - GET /
*1st we have to install mongodbcompass and add the database like crud in that
we can create new collection ex:users and add the data
2. open the terminal in vs code and type npm init –y (//then package.json file
will be created)
app.listen(3001,() =>{
console.log("server is running")
})
Output:
MODEL OBJECT:
When you define a Mongoose schema and then compile it into a Model using
`mongoose.model()`, you create an instance of the Model object. This Model
object allows you to perform CRUD (Create, Read, Update, Delete) operations
on documents that adhere to the schema.
Here's a breakdown of what a Model object does:
2. **Validation and Type Casting**: When you create documents using the
Model object's methods, Mongoose automatically validates the data against
the schema's defined structure and types. It also performs type casting based
on the schema's definitions.
//program
Code in app.js
File: APP.JS
mongoose.connect("mongodb://localhost:27017/magesDB");
name: {
type: String,
require: true
},
power_type: {
type: String,
require: true
},
mana_power: Number,
health: Number,
gold: Number
})
name: "Takashi",
power_type: 'Element',
mana_power: 200,
health: 1000,
gold: 10000
});
mage_1.save();
name: "Steve",
power_type: 'Physical',
mana_power: "500",
health: "5000",
gold: "50"
})
mage_2.save();
output:
here the model will be saved in the given hierarchy that is mentioned in the
code(magesDB/images)
>node app.js
EXPERIMENT – 8
1. Project Setup:
Create a new Node.js project directory.
Initialize it with npm init -y (or yarn init -y).
Install Express: npm install express (or yarn add express).
2. Data Persistence (Choose One):
Databases: Select a database like MongoDB, PostgreSQL, MySQL, etc.
based on your project's requirements.
Install the appropriate database driver (e.g., mongoose for MongoDB).
In-Memory Storage: Consider using express-session or a similar library
for temporary data during the user's session (not recommended for
persistent data).
8.a)Program to perform various CRUD (Create-Read-Update-Delete)
operations using Mongoose library functions.
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
try {
// Replace with your logic to retrieve note details from database (e.g., using
Mongoose)
const note = await Note.findById(noteId);
if (!note) {
return res.status(404).json({ message: 'Note not found' });
}
res.json(note);
} catch (error) {
console.error(error);
res.status(500).json({ message: 'Internal server error' });
}
});
The route handler function async allows for asynchronous database
operations.
req.params.id extracts the noteId from the URL.
The placeholder Note.findById(noteId) should be replaced with your
actual database interaction code to fetch the note based on the ID.
Error handling checks for 404 Not Found if the note doesn't exist and 500
Internal Server Error for unexpected errors.
The successful response sends the retrieved note data in JSON format.
try {
// Replace with your logic to update note details in database (e.g., using
Mongoose)
const updatedDocument = await Note.findByIdAndUpdate(noteId,
updatedNote, { new: true });
if (!updatedDocument) {
return res.status(404).json({ message: 'Note not found' });
}
res.json(updatedDocument);
} catch (error) {
console.error(error);
res.status(500).json({ message: 'Internal server error' });
}
});
This route handles the PUT (update) request.
req.body is assumed to contain the updated note data in JSON format.
The placeholder Note.findByIdAndUpdate(noteId, updatedNote, {
new: true }) should be replaced with your actual database interaction
code to update the note. The new: true option ensures the updated
document is returned.
Error handling is similar to the GET route.
The successful response sends the updated note data in JSON format.
if (userId) {
res.send(`Welcome back, user ${userId}!`);
} else {
// Generate a new session ID and create a cookie
const sessionId = Math.random().toString(36).substring(2, 15);
res.cookie('userId', sessionId, { httpOnly: true, signed: true }); // Secure
flags
res.send('Hello, new user! Your session ID is: ' + sessionId);
}
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
8.d)Sessions
Session Management with Server-Side Sessions
Session management is crucial for web applications to track user state
(information) across multiple requests during a session. In this approach,
session data is stored on the server-side, often in a database or in-memory store,
and a unique identifier (session ID) is used to link that data to the user.
How it Works:
Session Creation: Upon user login or session initiation, the server generates a
unique session ID and stores it on the server-side (e.g., database).
Session ID Delivery: The session ID is typically sent to the client (user's
browser) in a cookie or embedded in the URL (less secure).
Subsequent Requests: With the session ID received, the user's browser
includes it in subsequent requests within the same session.
Server-Side Association: The server receives the session ID and retrieves the
associated session data from its storage mechanism.
Context Maintenance: Based on the retrieved session data, the server can
maintain user context and personalize their experience.
Session Expiration: Sessions can expire after a predefined time (inactivity) or
be explicitly terminated by the user logging out. Upon expiration, the server-
side session data is typically destroyed.
Write a program to explain session management using sessions.
const express = require('express');
const session = require('express-session'); // Middleware for session
management
const app = express();
const port = 3000;
const secret = 'your_secret_key'; // Replace with a strong secret key
app.use(session({
secret: secret,
resave: false, // Don't resave session if no changes
saveUninitialized: true, // Create session even if not modified
cookie: { secure: false } // Set to true for HTTPS only
}));
if (sessionData.username) {
res.send(`Welcome back, ${sessionData.username}!`);
} else {
// Generate a new session ID and store something in the session
req.session.username = 'Guest';
res.send('Hello, new user!');
}
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
We use express and express-session modules.
A secret key is defined for session encryption (replace with a strong key).
The express-session middleware is used to manage sessions.
We configure resave: false to avoid unnecessary saves and
saveUninitialized: true to create sessions even without initial data.
The cookie object configures session cookie behavior (set secure: true for
HTTPS).
The root route (/) checks if a username property exists in the session data.
If present, it welcomes the user by name.
If absent, it creates a new session with a username ('Guest') and welcomes
the new user.
The server listens on port 3000.
8.e)Why and What Security, Helmet Middleware- Implement security
features in myNotes application
Security in myNotes: Why and What
Importance of Security:
Type Assignment:
When creating a variable, there are two main ways TypeScript assigns a type:
Explicit
Implicit
Explicit Type:
Explicit type assignment are easier to read and more intentional.
Explicit - writing out the type:
Syntax:
let firstName: string = "Dylan";
Implicit Type:
Implicit - TypeScript will "guess" the type, based on the assigned value:
Syntax:
There are also 2 less common primitives used in later versions of Javascript and
TypeScript.
bigint - whole numbers and floating point values, but allows larger
negative and positive numbers than the number type.
symbol are used to create a globally unique identifier.
Special Types:
any:
any is a type that disables type checking and effectively allows all types to
be used.
EX:
//output:NaN
Unknown:
TypeScript will prevent unknown types from being used, as shown below
EX:
<script>
let val: unknown;
console.log(val);
val = true;
console.log(val);
val = 7;
val = Math.random();
console.log(val);
val = null;
console.log(val);
</script>
Output:
Undefined
True
7
0.766654
null
Undefined&null:
undefined and null are types that refer to the JavaScript
primitives undefined and null respectively.
EX:
let y: undefined = undefined;
console.log(typeof y); //undefined
let z: null = null;
console.log(typeof z); //object
The control statements help users specify the order of execution of the instructions present
in a program.
If, else if, if else if, switch, for, while , do while are some control flow statements.
if statement:
An if statement executes a statement based on a condition. If the
condition is truthy, the if statement will execute the statements inside its
body:
if-else statement:
If you want to execute other statements when the condition in the if
statement evaluates to false, you can use the if...else statement:
switch case:
The following shows the syntax of the switch...case statement:
EX:
FUNCTIONS:
TypeScript, as in most programming languages, a function is a block of reusable
code that performs a specific task when called or invoked. Functions allow you to
encapsulate logic, making your code more modular, easier to understand, and
easier to maintain.
Anonymous function:
In TypeScript, an anonymous function is a function without a name. Instead of
being declared with a function name, it's defined using the function keyword
followed by the parameter list (if any) and the function body. Anonymous
functions are commonly used as callback functions or when a function is only
used once and doesn't need a name.
Functions can also be assigned to variables, creating function expressions.
Function expressions can be named or anonymous.
Define an arrow function inside the event handler to filter the product array with the
selected product object using the productId received by the function. Pass the selected
product object to the next screen.
Parameter types:
Parameter types specify the types of values that a function expects to receive
when it is called. These are declared within the parentheses () after the function
name.
Default Parameter:
You can also provide default values for parameters using the syntax
parameterName: type = defaultValue.
Return Types:
Return types specify the type of value that a function will return after it has
finished executing. This is declared after the parameter list and colon : followed
by the return type.
Number Return Type:
In this example, the add function returns a value of type number. When you call
add(3, 5), it returns the sum of the two numbers, which is of type number.
Void Return Type: A function with a void return type indicates that it does not
return any value.
Consider that developer needs to declare a manufacturer's array holding 4 objects with
id and price as a parameter and needs to implement an arrow function - myfunction to
populate the id parameter of manufacturers array whose price is greater than or equ
Optional and Default Parameters:
Optional Parameters:
In TypeScript, you can mark parameters as optional by appending a ? after the
parameter name. Optional parameters must come after required parameters.
Default Parameters:
You can also provide default values for parameters using the syntax
parameterName: type = defaultValue.
These modules provide a comprehensive overview of key TypeScript concepts, including rest
parameters, interfaces, duck typing, and function types.
Experiment - 11
A)Aim:
Declare a productList interface that extends properties from two other declared
interfaces like Category, and Product as well as implementation to create a
variable of this interface type.
Source Code:
interfaceCategory {
categoryName: string;
}
interfaceProduct {
productName: string;
productId: number;
}
interfaceProductListextendsCategory, Product {
list: Array<string>;
}
constproductDetails: ProductList = {
catego
ryNa
me:'G
adget',
produ
ctNam
e:'Mo
bile',
produ
ctId:1
234,
list: ['Samsung', 'Motorola', 'LG']
};
constlistProduct = productDetails.list;
constpname: string = productDetails.productName;
console.log('Product
Name is ' + pname);
console.log('Product
List is ' + listProduct);
Output:
B)Aim:
Consider the Mobile Cart application, Create objects of the Product class and
place them into the productlist array.
Source Code:
interfaceProduct {
displayProductName: (prouctId:
number) =>string;
getProductDetails(): string[];
}
classGadgetimplementsProduct {
getProductDetails(): string[]
{ retur
n
['Sam
sung',
'LG',
'Moto'
];
}
displayProductName(productId: number): string
{if (productId
=== 101)
{ return'Product
Name is
Mobile';
} elseif ( productId === 201)
{ return'Product Name is Tablet';
}
}
getGadget(): string[] {
return ['Mobile', 'Tablet', 'iPad', 'iPod'];
}
}
constgadget: Product
= newGadget();
constproductName: string = gadget.displayProductName(101);
console.log(productName);
Output:
C)Aim:
Declare a class named - Product with the below-mentioned declarations: (i) productId as number
property (ii) Constructor to initialize this value (iii) getProductId method to return the message
"Product id is <id va>"
Source Code:
classProduct {
staticproductpri
ce:string:
productId:numb
er;
constructor(productId:
number) {
this.productId = productId;
}
getProductId(): string {
return'Product id is : ' + this.productId;
}
}
constproduct: Product = newProduct(1234);
console.log(product.ge
tProductId());
Output:
D)Aim:
Create a Product class with 4 properties namely productId, productName,
productPrice, productCategory with private, public, static, and protected access
modifiers and accessing them through Gadget class and its methods.
Source Code:
Class product {
staticproductPrice=150;
privateproductId: number; publicproductName: string; protectedproductCategory: string;
constructor(productId: number, productName ,
productCategory) {
this.productId = productId;
this.productName =
productName;
this.productCategory =
productCategory;
}
product id details
getProductId() {
console.log('The Product id is : ' + this.productId);
}
}
classGadgetextendsProduct {
productCategory property
getProduct(): void {
console.log('Product category is : ' + this.productCategory);
}
}
constg: Gadget = newGadget(1234, 'Mobile', 'SmartPhone');
g.getProduct();
g.getProductId();
console.log('Product name is : ' +
g.productName);
class name console.log('Product price is : $' + Product.productPrice);
Output:
Output:
EXPERIMENT – 12
TYPESCRIPT
Properties and Methods
a) Create a Product class with 4 properties namely productId and methods to
setProductId() and getProductId
In TypeScript, you can create a Product class with properties and methods as required. Here's
a sample implementation that includes a class called Product with one property, productId,
and methods setProductId() and getProductId() to set and get the value of productId,
respectively:
typescript
class Product {
// Private property to store the productId
private productId: number;
- The Product class has one private property, productId, which stores the product ID.
- The constructor accepts an optional parameter productId, which can be used to initialize the
productId when an instance is created.
- The setProductId() method takes an argument productId of type number and sets the
productId property of the instance.
- The getProductId() method returns the value of the productId property.
- The example usage creates an instance of the Product class, sets the productId to 101, and
retrieves the value using the getter method.
Module Name: Creating and using Namespaces
12(b) Create a namespace called ProductUtility and place the Product class definition in
it. Import the Product class inside productlist file and use it
In TypeScript, namespaces are a way to organize and encapsulate code within a logical
grouping, similar to modules. By defining a namespace, you can group related classes,
functions, and variables together, providing a clear and structured way to manage your code.
In this example, I'll demonstrate how to create a namespace called ProductUtility and define a
Product class within it. I'll then show how to import the Product class inside a productlist file
and use it.
### Step 1: Define the Namespace and Class
First, create a file named ProductUtility.ts and define the ProductUtility namespace with a
Product class inside it:
typescript
// ProductUtility.ts
- **Product class**: The class is defined within the ProductUtility namespace and includes
properties quantity and price, a constructor to initialize the properties, and a method
calculateTotalPrice() to calculate the total price.
- *Exporting the class*: The Product class is exported from the namespace using the export
keyword, so it can be used in other files.
Next, create a file named productlist.ts and import the Product class from the ProductUtility
namespace:
typescript
// productlist.ts
- **Importing the Product class**: The Product class from the ProductUtility namespace is
imported using the import keyword. The syntax import Product = ProductUtility.Product
imports the Product class and renames it to Product for use in this file.
- *Calculating the total price*: The calculateTotalPrice() method of the Product instance is
used to calculate the total price.
- *Logging the total price*: The calculated total price is logged to the console.
This demonstrates how you can create a namespace in TypeScript to group related code,
define a class within the namespace, and then import and use the class in another file.
Module Name: Creating and using Modules
12(c) Consider the Mobile Cart application which is designed as part of the functions in
a module to calculate the total price of the product using the quantity and price values
and assign it to a totalPrice variable
In TypeScript, you can design a module that calculates the total price of a product using the
quantity and price values and assign it to a totalPrice variable. Here's how you can structure
this module:
First, create a module file named CartModule.ts with the function to calculate the total price
and an interface to represent a product:
// CartModule.ts
In this module:
- **Interface Product**: This interface represents a product with quantity and price
properties.
3. *Importing Code:*
- Code from one module can be imported into another using the import keyword.
- When using named exports, you must specify the names of the exported values you want
to import.
- For default exports, you can import the default export using a different name if you wish.
4. *Organizing Code:*
- Modules allow you to organize your code in a logical and meaningful way by grouping
related functions, classes, and other code constructs into separate files.
- This separation of concerns makes the code easier to understand and maintain.
5. *Module Resolution:*
- TypeScript has a module resolution strategy that determines how to find and load
modules. The strategy can include searching the file system and using node_modules
directories to resolve module imports.
6. *Types of Modules:*
- TypeScript supports different module systems:
- *CommonJS*: The module system used by Node.js.
- *ES Modules*: The standard module system used in modern JavaScript.
- TypeScript can compile to either of these module systems, allowing you to use
TypeScript in a variety of runtime environments.
7. *Type Annotations and Interfaces:*
- In addition to exporting functions and classes, you can export interfaces to define the
shape of data structures, such as the Product interface in the CartModule.ts example.
- Type annotations provide type checking and help catch errors at compile time.
- For a Mobile Cart application, you might define a module with functions and interfaces
related to shopping cart operations, such as calculating the total price of products.
- By exporting the functions and interfaces from this module, you can import and use them in
other parts of your application, such as the user interface or the checkout process.
- This approach keeps your code organized, modular, and reusable.
Overall, using modules in TypeScript helps improve code organization, maintainability, and
reusability, and facilitates the creation of more complex and scalable applications.
Module Name: What is Generics, What are Type Parameters, Generic Functions,
Generic Constraints
12(d) Create a generic array and function to sort numbers as well as string values
Generics:
Generics in TypeScript allow you to write flexible and reusable code that can operate on a
variety of data types while maintaining type safety. Generics let you abstract over types,
making your code more versatile and adaptable. You can use generics in functions, classes,
and interfaces.
typescript
Copy code
function genericFunction<T>(param: T): T {
return param;
}
Here, T is a type parameter that can represent any data type. This function accepts an
argument of type T and returns the same type T.
Type Parameters
Type parameters are placeholders for actual data types that are provided when you use a
generic function, class, or interface. For example, in the function genericFunction<T>(param:
T): T, the T is a type parameter.
When you use a generic function, class, or interface, you specify the actual type for the type
parameter:
typescript
Copy code
let result = genericFunction<number>(42);
Here, the type parameter T is replaced with the actual type number.
Generic Functions
A generic function allows you to write a function that can work with different types of data.
The function signature includes one or more type parameters. The type parameters are used to
specify the types of the function's arguments and return value.
For example:
typescript
Copy code
function reverseArray<T>(arr: Array<T>): Array<T> {
return arr.reverse();
}
Generic Constraints
Generic constraints allow you to specify requirements for the types used in a generic
function, class, or interface. This is done using the extends keyword. The constraint ensures
that the type parameter meets certain conditions, such as implementing a specific interface or
having certain properties.
For example:
typescript
Copy code
interface Comparable {
compareTo(other: any): number;
}
Conclusion
Generics in TypeScript are a powerful feature that allow you to write flexible and type-safe
code that can operate on various data types. By using type parameters and generic constraints,
you can ensure that your code behaves correctly and safely with different types of data.