0% found this document useful (0 votes)
5 views332 pages

Javascript

The document provides an overview of JavaScript, detailing its client-side functionalities, issues, and evolution. It explains how to integrate JavaScript into HTML, including inline, embedded, and external methods, as well as various techniques for selecting and manipulating DOM elements. Additionally, it covers output techniques available in JavaScript for rendering results on the user interface.

Uploaded by

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

Javascript

The document provides an overview of JavaScript, detailing its client-side functionalities, issues, and evolution. It explains how to integrate JavaScript into HTML, including inline, embedded, and external methods, as well as various techniques for selecting and manipulating DOM elements. Additionally, it covers output techniques available in JavaScript for rendering results on the user interface.

Uploaded by

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

JAVASCRIPT

Page -1

What is JavaScript?

JavaScript Client Side

- JavaScript is used client side to reduce burden on server.

- JavaScript handles

a) BOM Interactions [Browser Object Model]

b) DOM Interactions [Document Object Model]

c) Validation etc.

- BOM Interactions

a) Window Manipulations

b) Location

c) History

d) Browser Navigator etc.

- DOM Interactions

a) Data Binding

b) Style Binding

c) Class Binding

d) Event Binding etc.


- Validations

a) Verifying user input

b) Authorizing user data etc.

Issues with JavaScript

- It is not a strongly typed language.

x = 10; // number

x = “A”; // string - valid

x = true; // boolean - valid

- It is not implicitly strictly typed language.

- It requires explicit strict configuration by using the statement

“use strict”;

- It is not an OOP language, it supports only few features of OOP.

- Limited extensibility.

- No code level security.

Note: Typescript is an alternative for JavaScript.

Evolution of JavaScript:

- CERN labs developed a script called ECMA Script for Mosaic Browser.

[Council for European Research and Nuclear]


- Netscape Communications developed a browser called Netscape Navigator in early

1994-1995.

- Netscape appointed Brendan Eich to develop a script for their browser.

- He developed a script by name “Mocha” later renamed as “LiveScript”.

- Netscape given the responsibility of LiveScript to “Sun Microsystems”.

- LiveScript changed to JavaScript. [renamed by Sun & Netscape]

- Netscape stopped its services in early 2000’s.

- Netscape given the responsibility of JavaScript to ECMA International.

ECMAScript 2015 ES5

ECMAScript 2016 ES6

ECMAScript 2017 ES7

ECMAScript 2025 ES16 [latest - June 2025]

Integrating JavaScript into HTML page:

1. Inline

2. Embedded

3. External File

JavaScript Inline
- You can write JavaScript functions directly for HTML element in design.

- It is faster in interactions.

- You can’t reuse or extend.

Syntax:

<button onclick=“[Link]()”> Print </button>

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

</head>

<body>

<h1>Your Ticket</h1>

<button onclick="[Link]()">Print</button>

</body>

</html>
Page -2

JavaScript Integration with HTML page

1. Inline

2. Embedded

3. External File

JavaScript Inline

- You can configure JavaScript function directly for any element in design.

- It is faster in interactions.

- It is not good for reusability and extensibility.

Syntax:

<button onclick=“[Link]()”> Print </button>

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">


<title>Document</title>

</head>

<body>

<h1>Your Ticket</h1>

<button onclick="[Link]()">Print</button>

</body>

</html>

JavaScript Embedded

- JavaScript functions are written in a <script> container and embedded into <head> or <body>

- It is easy to reuse and extend.

- However it is not accessible across pages.

Syntax:

<script>

function PrintPage()

[Link]();

</script>

<button onclick=“PrintPage()”> Print </button>


- The MIME type for JavaScript depends on how you want to use JavaScript.

<script type=“text/javascript”> // If you are using interpreter in browser

<script type=“text/babel”> // If you are using babel as compiler

<script type=“module”> // If you are using a module system.

- You can turn ON strict mode in embed or external file by using “use strict”.

<script type=“text/javascript”>

“use strict”;

… your functions …

</script>

- You can target script for legacy browsers by enclosing the code in HTML comment block.

<!--

function Name()

-->
Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script type="text/javascript">

"use strict";

<!--

function PrintPage() {

[Link]();

-->

</script>

</head>

<body>

<h1>Your Ticket</h1>

<button onclick="PrintPage()">Print</button>

</body>

</html>
JavaScript from External File:

- You can write JavaScript functions in a separate script file with extension “.js”

- You can minify by using minification tools for production.

- Link the script file with any page.

- However external files will increase number of requests and also page load time.

Ex:

1. Src/scripts/[Link]

"use strict";

function PrintPage() {

[Link]();

2. Js-examples/[Link]

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script type="text/javascript" src="../src/scripts/[Link]">

</script>

</head>

<body>

<h1>Your Ticket</h1>

<button onclick="PrintPage()">Print</button>

</body>

</html>

JavaScript Reference Techniques

- JavaScript selects HTML elements to transform static DOM into dynamic DOM.

- There are various reference techniques to refer and select elements in page.

1. Refer by using DOM hierarchy

- HTML presents elements in a hierarchy called DOM.

- JavaScript can use DOM hierarchy to refer elements.

- It is the native technique of referring elements.

- Hence it is faster in interactions.

- However referring DOM uses an index of element, which need to be updated every time
when element changes position in design.

Syntax:

[Link][index].property = value;

[Link][index].elements[index].property = value;

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function bodyload(){

[Link][0].src = "../public/images/[Link]";

[Link][0].elements[1].value = "Login";

[Link][1].elements[2].value = "Register";

</script>

</head>

<body onload="bodyload()">
<div>

<img width="100" height="100">

</div>

<div>

<form>

<h3>Login</h3>

<input type="text" placeholder="User Id"> <input type="button">

</form>

</div>

<div>

<form>

<h3>Register</h3>

<input type="text" placeholder="User Name">

<br><br>

<input type="password" placeholder="Password">

<br><br>

<input type="button">

</form>

</div>

</body>

</html>
2. Refer by using name

- HTML can set a reference name for every element.

- JavaScript can access elements directly by reference name.

- You can’t refer any generic child element directly without referring to its parent.

- HTML can define same name for multiple elements, which will lead to reference issued in JavaScript.

Syntax:

<img name=“poster”>

<form name=“frm”>

<input type=“button” name=“btn”>

</form>

[Link]=“path”;

[Link] = “value”;

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">


<title>Document</title>

<script>

function bodyload(){

[Link]="../public/images/[Link]";

[Link] = "Login";

[Link] = "Register";

</script>

</head>

<body onload="bodyload()">

<div>

<img width="100" height="100" name="poster">

</div>

<div>

<form name="frmLogin">

<h3>Login</h3>

<input type="text" placeholder="User Id"> <input name="btnLogin" type="button">

</form>

</div>

<div>

<form name="frmRegister">

<h3>Register</h3>
<input type="text" placeholder="User Name">

<br><br>

<input type="password" placeholder="Password">

<br><br>

<input name="btnRegister" type="button">

</form>

</div>

</body>

</html>

3. Refer by using ID

- HTML element can have ID reference.

- JavaScript uses a document method “[Link]()” to access elements

by using ID.

- It can directly access element from any level of hierarchy without referring to parent.

- ID is a reference used for styles in CSS, which can conflict with JavaScript reference.

Syntax:

<img id=“poster”>

[Link](“poster”).src = “path”;
Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function bodyload(){

[Link]("poster").src="../public/images/[Link]";

[Link]("btnLogin").value = "Login";

[Link]("btnRegister").value="Register";

</script>

</head>

<body onload="bodyload()">

<div>

<img width="100" height="100" id="poster">

</div>

<div>

<form name="frmLogin">
<h3>Login</h3>

<input type="text" placeholder="User Id"> <input id="btnLogin" type="button">

</form>

</div>

<div>

<form name="frmRegister">

<h3>Register</h3>

<input type="text" placeholder="User Name">

<br><br>

<input type="password" placeholder="Password">

<br><br>

<input id="btnRegister" type="button">

</form>

</div>

</body>

</html>

4. Refer by using CSS selectors

- JavaScript can access elements using CSS selectors like

a) Relational

b) Attribute
c) Primary etc.

- It uses the document method “[Link]()”.

Syntax:

<img>

<input type=“button” id=“btnLogin”>

<input type=“button” class=“btn-primary”>

[Link](“img”).property = value;

[Link](“#btnLogin”).property = value;

[Link](“.btn-primary”).property = value;

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function bodyload(){

[Link]("img").src="../public/images/[Link]";
[Link]("#btnLogin").value = "Login";

[Link](".btn-register").value = "Register";

</script>

</head>

<body onload="bodyload()">

<div>

<img width="100" height="100">

</div>

<div>

<form name="frmLogin">

<h3>Login</h3>

<input type="text" placeholder="User Id"> <input id="btnLogin" type="button">

</form>

</div>

<div>

<form name="frmRegister">

<h3>Register</h3>

<input type="text" placeholder="User Name">

<br><br>

<input type="password" placeholder="Password">


<br><br>

<input class="btn-register" type="button">

</form>

</div>

</body>

</html>

Page- 3

Note: JavaScript provides various methods for referring multiple elements.

a) [Link]() b) [Link]()

c) [Link]() etc.

JavaScript Output Techniques:

- Output is the process of rendering result onto UI.

- JavaScript provides various techniques for handling output

1. alert()

2. confirm()

3. [Link]()

4. textContent

5. innerText
6. innerHTML

7. outerHTML

8. console methods

alert()

- It is a window method that renders output in a message box.

- It will not allow to cancel.

- It is used for mandatory confirmation.

- It will not allow to perform any another task in page until or unless you confirm.

Syntax:

alert(“message | expression”);

- It is RC type. It will not allow complex formats.

- You can add line break using “\n” .

Ex:

alert(“Welcome”);

alert( 10 + 20 );

alert( “Addition=“ + (10 + 20) );

alert( “line-1 \n line-2”);


- Alert returns “undefined” as type.

- Alert will not allow to customize the appearance.

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function DeleteClick(){

alert("Delete Record\nRecord Deleted successfully..");

</script>

</head>

<body>

<button onclick="DeleteClick()">Delete</button>

</body>

</html>
confirm()

- It is a window method similar to alert, but allows to cancel.

- It is a boolean method that returns

true : on OK

false : on Cancel

Syntax:

confirm(“message | expression”);

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function DeleteClick(){

choice = confirm("Delete Record\nAre you sure?");


if(choice==true){

alert("Deleted..");

} else {

alert("Canceled..");

</script>

</head>

<body>

<button onclick="DeleteClick()">Delete</button>

</body>

</html>

[Link]()

- It is an output method that renders output on new screen of same page.

- It can render message, expression or markup.

- It allows complex formats for message.

- However it is temporary and available until browser is opened.

Syntax:
[Link](“message | expression | markup”);

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function DeleteClick(){

choice = confirm("Delete Record\nAre you sure?");

if(choice==true){

[Link]("<h1 style='color:red'>Deleted</h1><p>Record deleted successfully</p><a


href='[Link]'>Back</a>");

} else {

alert("Canceled..");

</script>

</head>

<body>
<button onclick="DeleteClick()">Delete</button>

</body>

</html>

innerText & textContent

- Both techniques are similar and used to present output into any container element in

page.

- innerText is deprecated.

- textContent is new from ES5+ version.

- The container element must be an HTML element that can present text

<p> <h1> <div> <span> <dd> <dt> <header> <nav> etc.

- Both are RC type, they will not allow complex formats for content.

Syntax:

[Link](“p”).textContent = “message | expression”;

[Link](“div”).innerText = “message | expression”;

Ex:

<!DOCTYPE html>

<html lang="en">

<head>
<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function DeleteClick(){

choice = confirm("Delete Record\nAre you sure?");

if(choice==true){

[Link]("<h1 style='color:red'>Deleted</h1><p>Record deleted successfully</p><a


href='[Link]'>Back</a>");

} else {

[Link]("p").textContent = "Canceled..";

</script>

</head>

<body>

<button onclick="DeleteClick()">Delete</button>

<p></p>

</body>

</html>
innerHTML

- It is similar to innerText and textContent but allows complex formats.

- You can render markup into existing element.

- However the target element should not be RC type.

Syntax:

[Link](“p”).innerHTML = “message | expression | markup”;

[Link](“option”).innerHTML = “markup”; // markup not allowed

outerHTML

- It is similar to innerHTML but can replace the target element with current element

defined in markup.

Syntax:

[Link](“p”).innerHTML = “<h1> Welcome </h1>”

<p>

<h1> Welcome </h1>

</p>
[Link](“p”).outerHTML = “<h1> Welcome </h1>”

<h1> Welcome </h1> // <p> element is replaced.

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function DeleteClick(){

choice = confirm("Delete Record\nAre you sure?");

if(choice==true){

[Link]("<h1 style='color:red'>Deleted</h1><p>Record deleted successfully</p><a


href='[Link]'>Back</a>");

} else {

[Link]("p").outerHTML = "<h1>Canceled</h1>";

</script>
</head>

<body>

<button onclick="DeleteClick()">Delete</button>

<p></p>

</body>

</html>

Console Methods

- Console is a command line tool [CLI] of browser.

- It is available in browser developer tools.

- It is used by developers to test the commands.

- JavaScript can render output into the console.

- It is mostly used by developers for developers.

- It provides contextual methods

[Link]()

[Link]()

[Link]()

[Link]()

[Link]() etc.

Syntax:

[Link]( “message | expression” );


- It can’t present complex content. [formatted or markup] - Line break is defined using “\n”.

Ex:

[Link](“line-1 \n line-2”);

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function DeleteClick(){

[Link]("Delete Clicked");

choice = confirm("Delete Record\nAre you sure?");

if(choice==true){

[Link]("<h1 style='color:red'>Deleted</h1><p>Record deleted successfully</p><a


href='[Link]'>Back</a>");

} else {

[Link]("p").outerHTML = "<h1>Canceled</h1>";
[Link]("Cancel button clicked");

[Link]("Log message");

[Link]("<b>Information about task</b>\nLine-2");

</script>

</head>

<body>

<button onclick="DeleteClick()">Delete</button>

<p></p>

</body>

</html>

Page -4

JavaScript Input Techniques

- Input is the process of scanning value from user.

- User can provide a value to application, which is scanned and used for processing.

- JavaScript allows user to input a value into webpage by using following techniques

1. Query String
2. prompt()

3. Form elements

Query String

- It is a key and value collection.

- It is appended into URL with “?” Character.

- It can have multiple keys and value appended using “&”.

- It is in browser address bar.

- Hence user can input directly from browser address bar.

[Link] ? key1=value1 & key2=value2 & key3=value3 …

- JavaScript can access query string by using “[Link]”.

- “location” is a browser object and “search” is a property to read query string from browser.

- Query String is a string with various entities.

- You can convert the query string into a collection by using “URLSearchParams()”.

Syntax:

params = new URLSearchParams([Link]);

new => It is dynamic memory allocation operator.


[Link](key); // It returns value of specified key.

[Link]()

[Link]()

[Link]

[Link]()

[Link]()

[Link]() etc.

Ex: [Link]

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function bodyload(){

params = new URLSearchParams([Link]);

[Link]("p").innerHTML = "Category=" + [Link]("category") + "<br>Product="


+ [Link]("product") + "<br>Brand=" + [Link]("brand");

}
</script>

</head>

<body onload="bodyload()">

<h2>Search Results</h2>

<p></p>

</body>

</html>

URL: [Link]

Ex:

1. [Link]

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

</head>

<body>

<h3>Add Product</h3>
<form method="get" action="./[Link]">

<dl>

<dt>Name</dt>

<dd><input type="text" name="Name"></dd>

<dt>Price</dt>

<dd><input type="price" name="Price"></dd>

<dt>Category</dt>

<dd>

<select name="Category">

<option>Select Category</option>

<option>Electronics</option>

<option>Fashion</option>

</select>

</dd>

</dl>

<button type="submit"> Add Product </button>

</form>

</body>

</html>

2. [Link]
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<style>

dt {

font-weight: bold;

margin-bottom: 10px;

dd {

margin-bottom: 10px;

dl {

display: grid;

grid-template-columns: 3fr 9fr;

font-family: Arial;

</style>

<script>
function bodyload(){

params = new URLSearchParams([Link]);

[Link]("lblName").textContent = [Link]("Name");

[Link]("lblPrice").textContent = [Link]("Price");

[Link]("lblCategory").textContent = [Link]("Category");

</script>

</head>

<body onload="bodyload()">

<h2>Product Details</h2>

<dl>

<dt>Name</dt>

<dd id="lblName"></dd>

<dt>Price</dt>

<dd id="lblPrice"></dd>

<dt>Category</dt>

<dd id="lblCategory"></dd>

</dl>

<br><br>

<a href="./[Link]"> Back </a>

</body>
</html>

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function AddClick(){

params = new URLSearchParams([Link]);

[Link]("p").innerHTML = "Folder Added : " + [Link]("folder");

</script>

</head>

<body>

<button onclick="AddClick()"> + Add Folder</button>

<p></p>

</body>

</html>
prompt() :

- It is a JavaScript browser window method.

- It alerts an input box in browser window.

- User can input a value from input box.

Syntax:

prompt(“message”, “default_value”);

- Prompt returns the following

‘’ Empty string on OK click without value.

‘val’ String on OK click with value.

null On cancel click [with or without value]

Syntax:

data = prompt(“Message”, “default”);

if (data==null)

{
// action on cancel

else if (data==‘ ’)

// action on empty

else

// action on value submit

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function AddClick(){

data = prompt("Enter Folder Name","eg: Movies, Music, Softwares");

if(data==''){
alert('Please provide a folder name');

} else if(data==null){

alert('You canceled..');

} else {

[Link]("p").innerHTML += "Folder Added : " + data + "<br>";

</script>

</head>

<body>

<button onclick="AddClick()"> + Add Folder</button>

<p></p>

</body>

</html>

Form Input Elements:

- HTML form provides various input elements like textbox, checkbox, radio, dropdown,

number, password, date etc.

- JavaScript can handle input directly from form elements by accessing their values.

Syntax:
<input type=“text” id=“txtName”>

<select id=“lstCategories”>

[Link](“txtName”).value

[Link](“lstCategories”).value

Page-5

JavaScript Input Techniques

- Input is the process of scanning value from user.

- User can provide a value to application, which is scanned and used for processing.

- JavaScript allows user to input a value into webpage by using following techniques

1. Query String

2. prompt()

3. Form elements

Query String

- It is a key and value collection.

- It is appended into URL with “?” Character.

- It can have multiple keys and value appended using “&”.

- It is in browser address bar.

- Hence user can input directly from browser address bar.


[Link] ? key1=value1 & key2=value2 & key3=value3 …

- JavaScript can access query string by using “[Link]”.

- “location” is a browser object and “search” is a property to read query string from browser.

- Query String is a string with various entities.

- You can convert the query string into a collection by using “URLSearchParams()”.

Syntax:

params = new URLSearchParams([Link]);

new => It is dynamic memory allocation operator.

[Link](key); // It returns value of specified key.

[Link]()

[Link]()

[Link]

[Link]()

[Link]()

[Link]() etc.

Ex: [Link]
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function bodyload(){

params = new URLSearchParams([Link]);

[Link]("p").innerHTML = "Category=" + [Link]("category") + "<br>Product="


+ [Link]("product") + "<br>Brand=" + [Link]("brand");

</script>

</head>

<body onload="bodyload()">

<h2>Search Results</h2>

<p></p>

</body>

</html>

URL: [Link]
Ex:

1. [Link]

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

</head>

<body>

<h3>Add Product</h3>

<form method="get" action="./[Link]">

<dl>

<dt>Name</dt>

<dd><input type="text" name="Name"></dd>

<dt>Price</dt>

<dd><input type="price" name="Price"></dd>

<dt>Category</dt>

<dd>

<select name="Category">
<option>Select Category</option>

<option>Electronics</option>

<option>Fashion</option>

</select>

</dd>

</dl>

<button type="submit"> Add Product </button>

</form>

</body>

</html>

2. [Link]

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<style>

dt {
font-weight: bold;

margin-bottom: 10px;

dd {

margin-bottom: 10px;

dl {

display: grid;

grid-template-columns: 3fr 9fr;

font-family: Arial;

</style>

<script>

function bodyload(){

params = new URLSearchParams([Link]);

[Link]("lblName").textContent = [Link]("Name");

[Link]("lblPrice").textContent = [Link]("Price");

[Link]("lblCategory").textContent = [Link]("Category");

</script>

</head>

<body onload="bodyload()">
<h2>Product Details</h2>

<dl>

<dt>Name</dt>

<dd id="lblName"></dd>

<dt>Price</dt>

<dd id="lblPrice"></dd>

<dt>Category</dt>

<dd id="lblCategory"></dd>

</dl>

<br><br>

<a href="./[Link]"> Back </a>

</body>

</html>

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">


<title>Document</title>

<script>

function AddClick(){

params = new URLSearchParams([Link]);

[Link]("p").innerHTML = "Folder Added : " + [Link]("folder");

</script>

</head>

<body>

<button onclick="AddClick()"> + Add Folder</button>

<p></p>

</body>

</html>

prompt() :

- It is a JavaScript browser window method.

- It alerts an input box in browser window.

- User can input a value from input box.

Syntax:

prompt(“message”, “default_value”);
- Prompt returns the following

‘’ Empty string on OK click without value.

‘val’ String on OK click with value.

null On cancel click [with or without value]

Syntax:

data = prompt(“Message”, “default”);

if (data==null)

// action on cancel

else if (data==‘ ’)

// action on empty

else

// action on value submit


}

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function AddClick(){

data = prompt("Enter Folder Name","eg: Movies, Music, Softwares");

if(data==''){

alert('Please provide a folder name');

} else if(data==null){

alert('You canceled..');

} else {

[Link]("p").innerHTML += "Folder Added : " + data + "<br>";

</script>

</head>
<body>

<button onclick="AddClick()"> + Add Folder</button>

<p></p>

</body>

</html>

Form Input Elements:

- HTML form provides various input elements like textbox, checkbox, radio, dropdown,

number, password, date etc.

- JavaScript can handle input directly from form elements by accessing their values.

Syntax:

<input type=“text” id=“txtName”>

<select id=“lstCategories”>

[Link](“txtName”).value

[Link](“lstCategories”).value

Page -6

Summary
- Variable

- Declaration

- Assignment

- Initialization

- var, let, const

Var keyword:

- It configures a function scope variable.

- You can declare or initialize in any block and access from any another block.

- It allows declaration, assignment and initialization.

- It allows shadowing.

- Shadowing is the process of re-declaring or re-initializing same name identifier with in the

scope.

var x = 10; // initialization

x=20; // assignment

var x = 30; // shadowing

Ex:

<script>

function f1()
{

var x; // declaration

x = 10; // assignment

if(x==10)

var y = 20; // initialization

y = 30; // assignment

var y = 40; // shadowing

[Link]("x=" + x + "<br>y=" + y);

f1();

</script>

- It allows hoisting.

- Hoisting allows to use and declare variables without any order dependency.

Syntax:

<script>

“use strict”;

x = 10;

[Link](x);
var x; // hoisting

</script>

Let Keyword:

- It configures a block scope variable.

- Block scope allows to access in the same block and in its inner blocks.

- The process of configuring a block with inner blocks is known as “Closure”.

- In a closure inner block members are not accessible to outer block.

- It allows declaring, assignment and initialization.

- It will not allow shadowing and hoisting.

Ex:

<script>

"use strict";

function f1()

let x; // declaring

x = 10; // assignment

if(x==10)

let y = 20; // intialization


y = 30; // assignment

[Link]("x=" + x + "<br>y=" + y);

f1();

</script>

Const Keyword:

- It configures a block scope variable.

- It allows only initialization.

- It will not allow declaring & assignment.

- It will not allow shadowing & hoisting.

Syntax:

const x; // invalid - initializaiton missing

const x = 10; // valid

x = 20; // invalid - assignment not allowed

Note: A constant can change using re-initializaiton.

It keeps value constant across multiple requests.


Global Scope for Variable:

- Global scope refers to context that is allows across multiple functions.

- You can declare or initialize a global variable using var, let & const keywords.

- You can configure a variable inside function and make it global in access by using

“window” object.

- “window” is a browser object, hence it is possible only when JS is running in browser.

Syntax:

[Link] = value;

Ex:

<script>

"use strict";

var x = 10;

let y = 20;

const z = 30;

function f1(){

window.a = 50;
[Link]("f1 x=" + x + "y=" + y + "z=" + z + "a=" + a + "<br>");

function f2(){

[Link]("f2 x=" + x + "y=" + y + "z=" + z + "a=" + a + "<br>");

f1();

f2();

</script>

Variable Naming:

- Name must start with an alphabet.

- Few special chars are allowed but not recommended.

_name; // intended to use internally. [ private ]

$name; // intended to refer library variable. [ library is a set of values & functions]

- Name can be alpha numeric but can’t start with number.

var sales_2025; // valid

var 2025_sales; // invalid

- It can’t be a keyword.
var class; // invalid

var do; // invalid

- It must speak what it is.

- It must be in camel case.

var product;

var products;

var productName;

var btnInsert;

- Name doesn’t have a limit for chars officially, however the max limit for chars on 64bit

memory can be upto 65535.

- Keyword for variable can span to multiple by using “,” delimiter.

var x, y, z; // valid

var x, y, z=10; // x=undefined, y=undefined, z = 10

var x=10, y, z=20; // x = 10, y=undefined, z = 20


var [x,y,z] = [10,20,30] // x = 10, y=20, z=30

Page -7

JavaScript Data Types

- Data type refers to data structure.

- It is about the type of data stored in memory and its behaviour.

- JavaScript is not a strongly typed language.

- It is implicitly typed or dynamically typed language.

- The data type in memory is determined according to the value initialized or assigned.

var x = 10; // x is number

x = “A”; // x is string

x = true; // x is boolean

- JavaScript can handle various types of data, which is classified into

a) Primitive Types

b) Non Primitive Types


Primitive Types:

- They are immutable types.

- They have a fixed range for values.

- The value range can’t change dynamically.

- They are stored in memory stack.

- Stack uses “Last-In-First-Out” mechanism [ LIFO ].

- JavaScript primitive types are

1. Number

2. String

3. Boolean

4. Null

5. Undefined

6. Symbol ] New types from

7. Big Int ] ES6+ version

Number Type

- Number type refers to a numerical value.

- JavaScript uses following types as numbers

Signed Integer - 20
Unsigned Integer 20

Floating Point 34.21

Double 234.42

Decimal 2345.34

Exponent 2e3 [ 2 x 10^3 = 2000 ]

Binary 0b1010

Hexadecimal 0x0101

Octa 0o745

Big Int 9483888212n [Safe Integer]

- JavaScript provides following methods to convert a numeric string into number.

a) parseInt()

b) parseFloat()

- A numeric string refers to any value starting with number.

parseInt(“24AB”) + 1 => 25

parseInt(“AB24”) + 1 => NaN

parseInt(“24AB25) + 1 => 25

parseInt(“10.45”) + 1 => 11
parseFloat(“10.45”) + 1 => 11.45

- JavaScript can verify number type by using the method “isNaN()”.

- It returns boolean true if input value is not number type.

if (isNaN(“A”))

// not a number;

else

// is a number;

Ex:

<script>

var rate = parseFloat(prompt("Enter Rate"));

if(isNaN(rate)){

alert("Please provide a valid number");

} else {

[Link]("Rate Increased by 1 :" + (rate+1));

}
</script>

- JavaScript provides various methods for presenting a number.

a) toFixed()

- It can fix a number to specific decimal places.

- It requires the count of fractions for number.

var price = 45000;

[Link](2); // 45000.00

b) toPrecision()

- It can slice a number to exact precision of chars starting from first index.

- Precision can round values.

- Precision count can’t be a number less than the integer digits.

var price = 45000.56784;

[Link](7); // 45000.57

c) toLocaleString()
- It converts a number into a regional string.

- Regional string format contains various styles and notations.

- It requires a regional language type.

var price = 450000;

[Link](); // 450,000

[Link](‘en-in’); // 4,50,000

- It can use various styles

a) currency

b) decimal

c) percent

d) unit

[Link](‘en-in’, { style : “currency | percent | unit ..” } )

* currency requires various currency formats. [INR, USD etc.]

* unit requires various measuring units. [Kilogram, Litre, Pound etc..]

[Link](’en-in’, { style: “currency”, currency: “INR” } )

[Link](‘en-in’, { style: “unit”, unit: “kilogram” } )


- You can set minFractionDigits & maxFractionDigits to control fractions

in any string format.

[Link](‘en-in’, { style: “currency”, currency:”INR”,


minFractionDigits:0, maxFractionDigits:0 });

- Number can use various notations like

a) compact

b) scientific

c) metric etc.

[Link](‘en-us’, { notation: “compact” } );

Ex:

<script>

var views = 6450000;

[Link]([Link]('en-us', { notation:"compact" }) + " views");

</script>

Ex:

<script>
var price = 450000;

var weight = 72;

[Link]("Price=" + [Link]('en-in',{style:"currency", currency:"INR",


minimumFractionDigits:0, maximumFractionDigits:0}) + "<br>");

[Link]("Weight=" + [Link]('en-in', {style:"unit", unit:"kilogram"}));

</script>

Page -8

Summary

- Number Type

- Parsing Methods

a) parseInt()

b) parseFloat()

- isNaN()

- Formatting Methods

a) toFixed()

b) toPrecision()

c) toLocaleString()

- Format Style

a) currency

b) decimal

c) unit
d) percent

- Format Notation

a) scientific

b) metric

c) compact

d) engineering

String Type

- String is a literal with group of chars enclosed in

a) Double Quotes “ ”

b) Single Quotes ‘ ’

c) Back Ticks ` `

- String literal can have alphabet, number or special character.

- Double and Single quotes are used for outer and inner strings.

Syntax:

var link = “<a href=‘path’> Text </a>”;

var link = ‘<a href=“path”> Text </a>’;

- Double and Single quote requires lot of concat techniques to bind dynamic values.
“string” + value + “string”;

- ES5+ version provides back tick that allows embedded expression using “${ }”.

- It is a data binding expression to bind dynamic values, but it is allowed only in string with backticks.

`string ${value} string`;

Ex:

<script>

var user = prompt("Enter Name");

var age = parseInt(prompt("Enter Age"));

var msg1 = "Hello !&nbsp;" + user + "&nbsp;your age will be&nbsp;" + (age+1) + "&nbsp;next year.<br>";

var msg2 = `Hello ! ${user} your age will be ${age+1} next year.`;

[Link](msg1);

[Link](msg2);

</script>

- Backtick allows inner string with both double and single quotes.

`outer “inner” outer`;

`outer ‘inner’ outer`;


- Few special chars in a string are not printable. You can print non-printable chars using “\”,

var path = “d:\projects\js-project”; => d:projectsjs-project

var path = “d:\\projects\\js-project”; => d:\projects\js-project

Ex:

<script>

var path = "\"d:\\projects\\js-projects\"";

[Link](path);

</script>

String Formatting Methods:

- JavaScript provides various methods to format a string dynamically.

- Format includes font, size, color, styles etc.

bold()

italics()

strike()

sup()

sub()

fontsize()
fontcolor()

toUpperCase()

toLowerCase() etc.

- Several formatting methods are not allowed on RC type. Always use with innerHTML.

Syntax:

“string”.fontsize(‘2’).fontcolor(‘red’).bold().italics()

Events:

onkeyup : specifies actions to perform a every keyup inside element.

onblur : specifies actions to perform when element looses the focus.

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function VerifyUser(){
var username = [Link]("user").value;

var lblMsg = [Link]("lblMsg");

if(username=="david_nit"){

[Link] = "User Name Taken - Try Another".fontcolor('red').fontsize(3).italics();

} else {

[Link] = "User Name Available".fontcolor('green').bold();

function ChangeCase(){

var code = [Link]("code").value;

[Link]("code").value = [Link]();

</script>

</head>

<body>

<dl>

<dt>User Name</dt>

<dd><input type="text" onkeyup="VerifyUser()" id="user"></dd>

<dd id="lblMsg"></dd>

<dt>Bank IFSC Code</dt>

<dd>

<input type="text" onblur="ChangeCase()" size="10" id="code">


</dd>

</dl>

</body>

</html>

String Manipulation:

- JavaScript provides various methods to manipulate a string dynamically.

- Manipulation includes adding, replacing, filter, sorting, searching etc.

1. length

- It is a property that returns the total count of chars in a string.

- Count includes blank spaces.

Syntax:

var msg = “Welcome”;

[Link]; => 7

Ex:

<!DOCTYPE html>

<html lang="en">

<head>
<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function VerifyUser(){

var username = [Link]("txtUser").value;

var lblUser = [Link]("lblUser");

if([Link]==0){

[Link] = "User Name Required".fontsize(2).fontcolor('red');

} else {

if([Link]<4){

[Link] = "User name too short".fontsize(2).fontcolor('red');

} else {

[Link] = "";

function VerifyComments(){

var comments = [Link]("txtComments").value;

var maxlimit = 100;

var lblStatus = [Link]("lblStatus");

[Link] = `${[Link]} chars left


[${[Link]}/100]`.fontcolor('gray').fontsize(2);

</script>

</head>

<body>

<dl>

<dt>User Name</dt>

<dd><input type="text" onblur="VerifyUser()" onkeyup="VerifyUser()" id="txtUser"></dd>

<dd id="lblUser"></dd>

<dt>Your Comments</dt>

<dd>

<textarea id="txtComments" rows="4" onkeyup="VerifyComments()" maxlength="100" cols="40"></


textarea>

</dd>

<dd id="lblStatus"></dd>

</dl>

</body>

</html>

2. charAt()

- It returns the character at specified index.


- Index starts with “0”, which refers to first char.

Syntax:

var msg = “Welcome”;

[Link](0); // W

[Link](6); // e

3. charCodeAt()

- It returns the ASCII code of character at specified index.

- Character code

A = 65, Z=90

a = 97, z=122

Syntax:

var msg = “Ajay”;

[Link](0); // 65

[Link](2); // 97

Ex:

<!DOCTYPE html>

<html lang="en">

<head>
<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function VerifyName(){

var username = [Link]("txtName").value;

var lblName = [Link]("lblName");

if([Link](0)>=65 && [Link](0)<=90){

[Link] = "";

} else {

[Link] = "Name must start with uppercase letter".fontsize(2).fontcolor('red') +


`<br>Your name is starting with '${[Link](0)}' char.`.fontcolor('red').fontsize(2);

</script>

</head>

<body>

<dl>

<dt>User Name</dt>

<dd><input type="text" onblur="VerifyName()" id="txtName"></dd>

<dd id="lblName"></dd>

</dl>
</body>

</html>

Page -9

String Type

- Formatting Method

- Manipulation

1. length

2. charAt()

3. charCodeAt()

4. indexOf()

- It returns the first occurrence index of given character in a string.

- If character not found then it return “-1”.

5. lastIndexOf()

- It returns the last occurrence index number of given character.

Syntax:
var str = “Welcome”;

[Link](“e”); // 1

[Link](“e”); // 6

[Link](“a”); // -1

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function VerifyEmail(){

var email = [Link]("txtEmail").value;

var lblEmail = [Link]("lblEmail");

if([Link]("@")==-1){

[Link] = "Invalid Email".fontcolor('red').fontsize(2);

} else {

[Link] = "";

}
}

</script>

</head>

<body>

<dl>

<dt>Email</dt>

<dd><input onblur="VerifyEmail()" type="text" id="txtEmail"></dd>

<dd id="lblEmail"></dd>

</dl>

</body>

</html>

6. startsWith()

- It returns boolean true if string starts with specified char(s).

7. endsWith()

- It returns true if string ends with specified char(s).

Syntax:

var str = “[Link]”;

[Link](“outlook”); // false

[Link](“gmail”); // true
[Link](“in”); // false

[Link](“com”); // true

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/[Link]">

<script>

function VerifyCard(){

var card = [Link]("txtCard").value;

var imgCard = [Link]("imgCard");

if([Link]("4455")){

[Link]= "../public/images/[Link]";

} else {

[Link]= "../public/images/[Link]";

}
function VerifySkype(){

var skype = [Link]("txtSkype").value;

var lblSkype =[Link]("lblSkype");

if([Link]("[Link]")){

[Link] = "";

} else {

[Link] = "Invalid Skype ID".fontcolor('red').fontsize(2);

</script>

</head>

<body class="container-fluid">

<h3>Verify Details</h3>

<dl class="w-25">

<dt>Your Card Number</dt>

<dd class="input-group">

<input type="text" maxlength="16" onkeyup="VerifyCard()" id="txtCard" class="form-control">

<img class="input-group-text" width="70" id="imgCard">

</dd>

<dt>Your Skype ID</dt>

<dd>

<input onblur="VerifySkype()" type="text" placeholder="@[Link]" id="txtSkype" class="form-


control">

</dd>

<dd id="lblSkype"></dd>

</dl>

</body>

</html>

8. slice()

- It is used to extract the chars between specified index.

- It uses start and end index.

- The end index must be a value greater than start index.

Syntax:

[Link](startIndex, endIndex)

9. substr()

- It returns the specified number of chars from given position.

- It uses a start index and count of chars.

- Count must be a number greater than zero.

Syntax:
[Link](startIndex, count_of_chars);

10. substring()

- It returns the chars between specified index.

- It uses start and end index.

- It is bi-directional in reading. [ towards start & end ]

Syntax:

[Link](startIndex, endIndex);

- It can have end index upto 0 [start] or max [end].

Ex:

<script>

var msg = "Welcome to JavaScript";

[Link]([Link](8,0) + "<br>");

</script>

Task:

var email = prompt(“Enter Email”); // something_123@[Link]

// info@[Link]
var id = [Link](0, [Link](“@“)); something_123, info

var domain = [Link]([Link](“@“)+1); [Link], [Link]

Task:

var queryString = “[Link]?product=mobile”;

var key = ?

var value = ?

with string methods access key and value.

Ex:

<script>

var queryString = "[Link]?category=electronics";

var questionPosition = [Link]("?");

var equalPosition = [Link]("=");

var key = [Link](questionPosition+1, equalPosition);

var value = [Link](equalPosition+1);

[Link](`Key=${key}<br>Value=${value}`);

</script>
11. replace()

- It can find and replace first occurrence of a string with another.

- It requires old and new string.

12. replaceAll()

- It can find and replace all occurrences in a string.

Syntax:

[Link](“old”, “new”);

[Link](“old”, “new”);

Ex:

<script>

var msg = "JS Tutorial, JS Projects, JS Examples";

[Link]([Link]("JS", "JavaScript"));

</script>

13. trimStart()

- It removes the blank spaces at the start of string.


14. trimEnd()

- It removes the leading spaces in a string. [ at the end ]

15. trim()

- It removes the blank spaces at the start and end of string.

Syntax:

[Link]()

[Link]()

[Link]()

Ex:

<script>

var password = prompt("Enter Password");

if([Link]()=="admin"){

[Link]("Login Success..");

} else {

[Link]("Invalid Password");

</script>

Page-10
16. match()

- It is used to verify string with regular expression.

- It is a boolean method that return true if string is matching with expression.

- Regular expression is built by using

a) Meta Characters

b) Quantifiers

- Expression is enclosed in “/ /“.

Syntax:

if ([Link]( / expression / )

// on true;

else

// on false;

Ex:

<!DOCTYPE html>

<html lang="en">
<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/[Link]">

<script>

function VerifyPassword(){

var password = [Link]("txtPwd").value;

var lblPwd = [Link]("lblPwd");

var regExp = /(?=.*[A-Z])\w{4,15}/;

var progressBar = [Link]("progressBar");

if([Link]==0){

[Link] = "Password Required".fontcolor('white');

} else {

if([Link](regExp)){

[Link] = "Strong Password".fontcolor('white');

[Link] = "100%";

[Link] = "progress-bar progress-bar-striped progress-bar-animated bg-


success";

} else {

if([Link]<4){
[Link] = "Poor Password".fontcolor('white');

[Link] = "30%";

[Link] = "progress-bar progress-bar-striped progress-bar-animated bg-


danger";

} else {

[Link] = "Weak Password".fontcolor('white');

[Link] = "70%";

[Link] = "progress-bar progress-bar-striped progress-bar-animated bg-


warning";

</script>

</head>

<body class="container-fluid">

<h3>Register</h3>

<dl class="w-25">

<dt>Password</dt>

<dd><input type="password" onkeyup="VerifyPassword()" id="txtPwd" class="form-control"></dd>

<dd>

<div class="progress">
<div class="progress-bar" id="progressBar">

<span id="lblPwd"></span>

</div>

</div>

</dd>

</dl>

</body>

</html>

17. split()

- It splits the string a specified delimiter and returns an array of strings.

Syntax:

var msg = “Welcome to JavaScript”;

[Link](‘ ’); // [ “Welcome”, “to”, “JavaScript” ]

0 1 2

Ex:

<script>

var contacts = "John-9588382111, David-938288222";

var [john, david] = [Link](','); // [john-99, david-93]

[Link]([Link]('-')[1]);
</script>

Task :

var email = prompt(“Enter Email”); // something@[Link]

var id = ?

var domain= ?

Using split method.

<script>

var email = prompt("Enter Email");

var [id, domain] = [Link]('@');

[Link](`Id=${id}<br>Domain=${domain}`);

</script>

18. includes()

- It is a boolean method that returns true if string contains specified chars. - It uses a search string
to verify content in element.

Syntax:

if ([Link](searchString))
{

Note: You need iterators or loops for read every element from a collection.

Syntax:

for(var item of collection)

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function Search(){

var searchString = [Link]("txtSearch").value;

var listItems = [Link]("li");

for(var item of listItems){


if([Link](searchString)){

[Link] = "block";

} else {

[Link] = "none";

</script>

</head>

<body>

<input type="text" id="txtSearch" onkeyup="Search()" placeholder="Search Topics">

<ul>

<li> JavaScript Tutorial </li>

<li> HTML Tutorial </li>

<li> JavaScript Projects </li>

<li> JavaScript Examples </li>

<li> CSS Tutorial </li>

<li> CSS Projects </li>

<li> HTML Examples </li>

</ul>
</body>

</html>

Boolean Type

- Boolean is used in decision making.

- Boolean can handle “true” or “false” as values.

- JavaScript boolean can use “1” for true and “0” for false.

- However it is always recommended to use true & false keywords.

- You can control various boolean properties of HTML elements

a) open

b) required

c) readonly

d) selected

e) checked

f) disabled etc.

Syntax:

[Link] = true; // Good

[Link] = 1; // OK but not Good

true + true = ? 2
true + “A” = ? trueA

“A” + “B” = AB

10 + “A” = 10A

“A” - “B” = NaN

“A” * 2 = NaN

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function VerifyName(){

var username = [Link]("txtName").value;

var btnSubmit = [Link]("btnSubmit");

if([Link]==0){

[Link] = true;

} else {

[Link] = false;
}

function ToggleAds(){

var dialog = [Link]("dialog");

var checkbox = [Link]("optShow");

if([Link]==true){

[Link] = true;

} else {

[Link] = false;

</script>

</head>

<body>

<input type="checkbox" onchange="ToggleAds()" id="optShow"> <label>Show Ads</label>

<dialog>

<h4>Ads</h4>

<img src="../public/images/[Link]" width="100" height="100">

</dialog>

<dl>

<dt>User Name</dt>

<dd><input type="text" onkeyup="VerifyName()" id="txtName"></dd>


</dl>

<button id="btnSubmit" disabled>Submit</button>

</body>

</html>

Page-11

Summary

- Number

- String

- Boolean

Undefined:

- It is a type configured for variables which are not defined with a value.

- If variable is declared and value is not initialized or assigned then compiler sets as

“undefined”.

- You can verify by using “undefined” keyword.

Syntax:

var x ;

[Link](x); x = undefined
if (x==undefined) => not good

if(x) => JS will return true if value is defined in “x” reference. // good

Ex:

<script>

var price;

if(price){

[Link](`Price=${price}`);

} else {

[Link](`Price is not defined`);

</script>
Null Type:

- It refers to “no-value” at run time.

- If a reference is expecting value at compile time and it is not specified then it is set with

“undefined”.

- If a reference is expecting value at runtime and it is not specified then it return null.

undefined : compile time no value

null : run time no value

Syntax:

var name = prompt(“Enter Name”); // returns null on cancel.

if(name== null)

Symbol Type:

- It is new data of JS from ES6 version.

- It is used to configure a unique hidden field for object.

- It is hidden over iterations, but available to access individually.

Syntax:
var id = Symbol();

var obj = {

[id] : 1

Non Primitive Types:

- They are mutable types.

- Their reference can be changed.

- They don’t have a fixed range for value.

- Value range varies according to memory availability.

- They are stored in a heap memory.

- Heap doesn’t have any order of accessing.

- JavaScript non primitive types are

a) Array

b) Object

c) Map

Array Type:

- Arrays are used in computer programming to reduce overhead and complexity.


- Array reduces overhead by storing values in a sequential order.

- Array can reduce complexity by storing multiple values under one reference name.

- JavaScript array can handle various types of values in sequential order.

- JavaScript array size can change dynamically.

- Few technologies may restrict array to similar type and will not allow to change size

dynamically.

- Array is a type of arrangement for values in sequential order that allows to access in

random.

Configuring Array:

1. Array requires a declaration, which you can defined using “var, let, const” keywords.

2. It requires initialization or assignment of memory to handle multiple values.

3. Memory for multiple values can be configures in 2 ways

a) [ ] Array meta character

b) new Array() Array constructor

Assignment of Memory

var data;

data = [ ];
(or)

data = new Array();

Initialization of Memory

var data = [ ];

(or)

var data = new Array();

FAQ: What is difference between Array() and [ ] ?

Ans: Array constructor uses dynamic memory, which is newly allocated on every request.

[ ] meta character uses static memory, which is good for continuous operations.

Page-12

Array

Array Configuration

[]

Array()

Array Elements:
- Array is a collection of elements in sequential order.

- Array element is stored and accessed by using a property reference.

- Property is a string type that maps to relative index in memory.

Syntax:

let data = [ ];

data[0] = 10; // valid

data[“1”] = “John”; // valid

[Link](data[“0”] + “\n” + data[1]); // valid

Ex:

<script>

var data = [10, "A", true];

data["3"] = 20;

data[4] = false;

for(var property in data){

[Link](`${property}[${typeof property}]: ${data[property]}[${typeof data[property]}]<br>`);

</script>
- Array element can be any type.

a) Primitive

b) Non Primitive

c) Function

- If array memory is defined with a function, then it must be anonymous type.

- Anonymous functions are invoked using IIFE technique.

[Immediately Invoking Function Expression]

Syntax:

var data = [ function(){ } ] ;

data[0](); // IIFE

Ex:

<script>

var data = [1, "A", true, ['Delhi', 'Hyd'], function(){[Link]('Function in Array Memory..')}];

[Link](data[3][1] + "<br>");

data[4]();

</script>
Ex:

<script>

var data = [[10, 20], [['Delhi', 'Hyd']]];

[Link](data[1][0][1]);

</script>

Array Manipulations:

1. Reading all array elements

toString() : It returns all elements separated with “,” delimiter.

join() : It returns all elements separated with custom delimiter.

Syntax:

[Link]();

[Link](‘ separator ’ );

Ex:

<script>

var data = [10, 20, 30, "A", "B", "C"];


[Link]([Link]() + "<br>");

[Link]([Link](' > ') + "<br>");

</script>

forEach() : It uses an iterator function to read every element from collection.

It can read the value and its index number.

It is void type and will not return any value.

Syntax:

[Link](function(value, index) {

})

“value & index” are formal names, you can defined any name.
The first param refers to value and second refers to index.

map() : It is similar to “forEach()” but returns an array of values.

It is good for reusability.

for..in : It reads and returns all properties of array.


for..of : It reads and returns all values of array.

Syntax:

for (var property in data) { }

for (var value of data) { }

Ex:

<script>

var data = [10, 20, 30, "A", "B", "C", "D"];

for(var property in data){

[Link](`[${property}]: ${data[property]} <br>`)

</script>

2. Reading Specific set of elements

slice() : It can read and returns elements between specified index.

Syntax:

[Link](startIndex, endIndex);
find() : It uses a function that finds and returns the first occurrence value

which matches the given condition.

It returns only one element.

filter() : It is similar to find but returns all elements that match given

condition.

Syntax:

[Link](function(value) {

return value_condition;

})

Ex:

<script>

var data = [13000, 60000, 57300, 62000, 67000, 12000];

var result = [Link](function(value){

return value>=60000;

});

[Link](result);

</script>
3. Array De-structure and Spread

- De-Structure is a new technique in JS that allows to separate array elements and

store into individual references.

Syntax:

let data = [10, 20, 30];

let [a,b,c] = data; // a=10, b=20, c=30

Syntax: without de-structure

let a = data[0];

let b = data[1];

let c = data[2];

- Spread is a new operator “…” of ES6 that allows to spread a collection into individual

elements.

Syntax:

let list1 = [10, 20];

let list2 = [30, 40];


let list3 = [list1, list2] ; // list 3 => have 2 elements

let list3 = […list1, list2]; // list3 => have 3 elements [10, 20, list2]

let list3 = […list1, …list2]; // list3 => have 4 elements [10, 20, 30, 40]

Ex:

<script>

let list1 = [10, 20];

let list2 = [30, 40];

let list3 = [...list1, ...list2];

[Link](list3);

</script>

Page -13

1. Reading all & specified Array Elements

2. De-Structure and Spread

4. Adding Elements into Array


push() Adds new item(s) as last element.

unshift() Adds new item(s) as first element.

splice() Adds new item(s) at specific position.

[Link](“item1”, “item2”, …);

[Link](“item1”, “item2”, …);

[Link](startIndex, deleteCount, “item1”, “item2”, …)

Note: To add items without deleting existing the delete count must be set to “0”.

Ex:

<script>

let data = ["A", "B", "D"];

[Link](2,0,"C","E");

[Link](function(value, index){

[Link](`[${index}]: ${value} <br>`);

})

</script>

5. Removing Elements from Array

pop() It removes and returns last item.


shift() It removes and returns first item.

splice() It removes and returns specific item.

[Link]()

[Link]()

[Link](startIndex, deleteCount)

6. Sorting array elements

sort() It arranges in ascending order.

reverse() It arranges in reverse order.

Note: You can’t sort numerical values, they are sorted as string.

[Link]().reverse()

Adding HTML elements dynamically

1. You can create any HTML element by using DOM method


[Link](“elementName”)

[Link](“p, img, table, td, input, button…”)

2. Assign to a memory reference

let ref = [Link](“name”);

3. Configure properties for element

[Link] = value;

[Link] | height | href | src | align | className | style etc.

4. Add element into page by using the method “appendChild()”. It requires a parent element to add
newly create element.

[Link](“body”).appendChild(ref);

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function UploadClick(){

var pic = [Link]("img");

[Link] = "100";

[Link] = "100";

[Link]= "../public/images/[Link]";

[Link]("container").appendChild(pic);

function MoreClick(){

var input = [Link]("input");

[Link] = "file";

[Link] = "block";

[Link] = "10px";

[Link]("files").appendChild(input);

function bodyload(){

var table = [Link]("table");

[Link]="1";

[Link] = "300";

var thead = [Link]("thead");


var thead_tr = [Link]("tr");

var th = [Link]("th");

[Link] = "Name";

thead_tr.appendChild(th);

[Link](thead_tr);

[Link](thead);

[Link]("data").appendChild(table);

</script>

</head>

<body onload="bodyload()">

<div id="data">

</div>

<button onclick="UploadClick()">Upload Photo</button>

<br><br>

<div id="container"></div>

<h3>File Upload</h3>

<div>

<input type="file"> <span> <button onclick="MoreClick()">more..</button> </span>

<div id="files">
</div>

</div>

</body>

</html>

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<style>

ol, select, nav {

margin-top: 20px;

margin-bottom: 20px;

nav {

background-color: black;

color:white;

padding: 10px;
display: flex;

justify-content: space-around;

nav a {

color:white;

</style>

<script>

var categories = ["All", "Electronics", "Fashion", "Footwear"];

var courses = ["../public/images/[Link]", "../public/images/[Link]", "../public/images/


[Link]", "../public/images/[Link]"];

function bodyload(){

[Link](function(item){

var li = [Link]("li");

[Link] = item;

[Link]("ol").appendChild(li);

var option = [Link]("option");

[Link] = item;

[Link] = item;

[Link]("select").appendChild(option);
var span = [Link]("span");

[Link]= `<a href='${item}.html'>${item}</a>`;

[Link]("nav").appendChild(span);

var ul_li = [Link]("li");

ul_li.innerHTML = `<input type="checkbox" value=${item}> <label>${item}</label>`;

[Link]("ul").appendChild(ul_li);

})

[Link](function(courseImagePath){

var img = [Link]("img");

[Link] = courseImagePath;

[Link]="100";

[Link]="100";

[Link] = "10px";

[Link]("header").appendChild(img);

})

</script>

</head>

<body onload="bodyload()">
<header>

</header>

<ol>

</ol>

<select>

</select>

<nav>

</nav>

<ul style="list-style: none; height: 50px; overflow: auto; border:1px solid gray; padding: 10px; width:
150px;">

</ul>

</body>

</html>

Ex:

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/[Link]">

<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/[Link]">

<script>

function bodyload(){

var courses = ["../public/images/[Link]", "../public/images/[Link]", "../public/images/


[Link]", "../public/images/[Link]"];

[Link](function(course){

var div = [Link]("div");

[Link] = "card p-2 m-2";

[Link] = "200px";

[Link] = `

<div class="card-header">

<img src=${course} class="card-img-top">

</div>

<div class="card-body text-center text-warning">

<span class="bi bi-star-fill"></span>


<span class="bi bi-star-fill"></span>

<span class="bi bi-star-fill"></span>

<span class="bi bi-star-fill"></span>

<span class="bi bi-star-fill"></span>

</div>

<div class="card-footer">

<button class="btn btn-warning w-100">Join</button>

</div>

`;

[Link]("section").appendChild(div);

})

</script>

</head>

<body class="container-fluid p-3" onload="bodyload()">

<section class="d-flex">

</section>

</body>

</html>
Page -14

Ex: Array Manipulations

1. Src/scripts/[Link]

var movies = [

"avatar : fire & ash",

"dhurandhar"

];

function LoadMovies(){

[Link]("lstMovies").innerHTML = "";

[Link](function(movie){

var option = [Link]("option");

[Link] = [Link]();

[Link] = movie;

[Link]("lstMovies").appendChild(option);

})

[Link]("lblCount").innerHTML = `Total Count of Movies : ${[Link]}`;


}

function AddClick(){

var movieName = [Link]("txtMovie").value;

if([Link]([Link]())==-1){

[Link]([Link]());

alert(`${[Link]()}\nAdded Successfully..`);

LoadMovies();

[Link]("txtMovie").value = "";

} else {

alert(`${[Link]()} exists`);

function SortAsc(){

[Link]();

LoadMovies();

function SortDesc(){

[Link]();

[Link]();

LoadMovies();
}

function DeleteClick(){

var selectedMovieName = [Link]("lstMovies").value;

var selectedMovieIndex = [Link](selectedMovieName);

var flag = confirm(`Delete Movie\nAre you sure want to delete ${selectedMovieName}`);

if(flag==true){

[Link](selectedMovieIndex,1);

LoadMovies();

function ClearClick(){

[Link] = 0;

LoadMovies();

function EditClick(){

var selectedMovieName = [Link]("lstMovies").value;

[Link]("txtEditMovie").value = selectedMovieName;

}
function SaveClick(){

var editedMovieName = [Link]("txtEditMovie").value;

var selectedMovieName = [Link]("lstMovies").value;

var selectedMovieIndex = [Link](selectedMovieName);

movies[selectedMovieIndex] = editedMovieName;

LoadMovies();

2. Js-examples/[Link]

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/[Link]">

<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/[Link]">

<script src="../node_modules/bootstrap/dist/js/[Link]"></script>

<script src="../src/scripts/[Link]"></script>
</head>

<body class="container-fluid p-4" onload="LoadMovies()">

<h3 class="bi bi-camera-reels"> Book My Show - Admin Dashboard</h3>

<div class="my-3 w-25">

<div class="input-group">

<input type="text" id="txtMovie" class="form-control" placeholder="New Movie Name">

<button onclick="AddClick()" class="btn btn-danger">Add</button>

</div>

</div>

<div class="my-3 w-25">

<div class="my-2">

<button onclick="SortAsc()" class="btn bi btn-warning bi-sort-alpha-down"></button>

<button onclick="SortDesc()" class="btn bi btn-warning bi-sort-alpha-up mx-2"></button>

</div>

<select class="form-select" size="3" id="lstMovies">

</select>

<div class="my-2">

<label id="lblCount" class="fw-bold form-label"></label>

</div>

<div class="my-2">
<button onclick="EditClick()" data-bs-target="#edit" data-bs-toggle="modal" class="btn btn-warning
bi bi-pen"> Edit</button>

<div class="modal fade" id="edit">

<div class="modal-dialog">

<div class="modal-content">

<div class="modal-header">

<h3>Edit Movie</h3>

</div>

<div class="modal-body">

<input type="text" id="txtEditMovie" class="form-control">

</div>

<div class="modal-footer">

<button onclick="SaveClick()" data-bs-dismiss="modal" class="btn btn-success"> Save</


button>

<button data-bs-dismiss="modal" class="btn btn-danger"> Cancel</button>

</div>

</div>

</div>

</div>

<button onclick="DeleteClick()" class="btn mx-2 btn-danger bi bi-trash-fill"> Delete</button>

<button onclick="ClearClick()" class="btn btn-outline-danger bi bi-trash"> Clear All</button>

</div>
</div>

</body>

</html>

Object Type

- Object is used to keep relative data and logic together.

- Object enables clean separation and reusability.

- Alan Kay introduced the concept of Object into computer programming in early 1960’s.

- Object is a key and value collection.

- Key is string type and value can be any type.

“key” : value,

“key” : value

- Key is accessible within object by using “this” keyword and outside object using

object name.

let tv = {
Name: “Samsung TV”,

Price: 45000,

Cities: [“Delhi”, Hyd”],

Rating: { Rate: 4.5, Count: 6000 }

[Link]; // It gets the value

[Link]=“New”; // It sets the value

- Object can configure logic by using “function”

let obj = {

key : value,

key : function(){

Ex:

<script>

let product = {

Name : "",
Price: 0,

Qty: 0,

Total : function(){

return [Link] * [Link];

},

Print: function(){

[Link](`Name=${[Link]}<br>Price=${[Link]}<br>Qty=${[Link]}<br>Total=
${[Link]()}`);

[Link] = "Samsung TV";

[Link] = 45000;

[Link] = 2;

[Link]();

[Link]("<hr>");

[Link] = "iPhone";

[Link] = 70000;

[Link] = parseInt(prompt("Enter Phone Qty"));

[Link]();

</script>
- If object comprises of only data then it is referred as “JSON” JavaScript object notation.

Page -15

AJAX

Object Type

- Key / Values

- Relative Data

JSON

- JavaScript Object Notation

- It is a representation of data

- It is light weight, uses less memory.

- It is cross platform, understandable to any device or OS services.

- It is not infected by VIRUS.

- It is not blocked by Firewalls.

Syntax:
{

“key”: value,

“key”: value

- Object manipulation requires following techniques.

1. Reading all keys from object

a) for..in

b) [Link]()

Syntax:

for(var key in object)

[Link](object) => [] of keys

Ex:

<script>

var product = {
Name: "TV",

Price: 45000,

Rating: 3.5

for(var key in product){

[Link](key + "<br>");

</script>

Ex:

<script>

var product = {

Name: "TV",

Price: 45000,

Rating: 3.5

[Link](product).map(function(key){

[Link](`${key}: ${product[key]}<br>`);

})

</script>

2. Delete a key by using “delete” operator


delete [Link];

If key is removed then it returns undefined.

3. You can verify the key by using “in” operator. It returns true if key is available.

if( “key” in object )

4. You can know the data type of value in a key by using “typeof” operator.

typeof [Link]; => number, string, boolean etc.

JavaScript Ajax

- AJAX is “Asynchronous Javascript And XML”.

- It enables “Partial Post back”.

- It can submit only a specific portion of page.


- It can add new details to page without reloading the complete page.

- It improves the performance of page.

- Browser handles AJAX by using “XMLHttpRequest” object.

1. Create a new XMLHttpRequest object

var http = new XMLHttpRequest();

2. Configure the request

[Link](“method”, “url”, “async:true/false”);

a) method : GET, POST, PUT, DELETE etc.

b) url : File location

c) async : true uses asynchronous request.

3. Send the request

[Link]();

4. Execute the request by using “onreadystatechange” event


[Link] = function() {

- Every request have 4 phases

1 Initial

2 Success

3 Complete

4 Ready

5. You have to access response data on ready phase.

if ([Link] == 4)

// [Link];

// [Link];

// [Link]; etc.

Ex:
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function LoadClick(){

var http = new XMLHttpRequest();

[Link]("get", "../data/[Link]", true);

[Link]();

[Link] = function(){

if([Link]==4){

[Link]("container").innerHTML = [Link];

function LoadMyntra(){

var http = new XMLHttpRequest();

[Link]("get", "../public/[Link]", true);

[Link]();

[Link] = function(){
if([Link]==4){

[Link]("frame").innerHTML = [Link];

</script>

</head>

<body>

<header>

<h1>Shopping Home</h1>

</header>

<section>

<button onclick="LoadClick()">Load Help</button>

<button onclick="LoadMyntra()">Myntra</button>

<br><br>

<div id="frame"></div>

<pre id="container">

</pre>

</section>

</body>
</html>

Ex: AJAX - Flipkart Product

1. Add a new folder “data” into project

2. Add a new file into data folder by name “[Link]”

"title": "Apple iPhone 16 (Pink, 256 GB)",

"price": 79000,

"rating": {"rate":4.4, "ratings":154568, "reviews":206},

"image": "../public/images/[Link]",

"offers": [

"Bank Offer5% cashback on Axis Bank Flipkart Debit Card up to ₹750T&C",

"Bank Offer5% cashback on Flipkart SBI Credit Card upto ₹4,000 per calendar quarterT&C",

"Bank Offer5% cashback on Flipkart Axis Bank Credit Card upto ₹4,000 per statement quarterT&C",

"Bank OfferUp To ₹50 Cashback on BHIM Payments App. Min Order Value ₹199. Offer Valid Once Per
User"

}
3. Add HTML page “[Link]”

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/[Link]">

<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/[Link]">

<script>

function bodyload(){

var product = {};

var http = new XMLHttpRequest();

[Link]("get", "../data/[Link]", true);

[Link]();

[Link] = function(){

if([Link]==4){

product = [Link]([Link]);

[Link]("imgProduct").src = [Link];

[Link]("title").textContent = [Link];

[Link]("rating").textContent = [Link];
[Link]("reviews").innerHTML = `
${[Link]('en-in')} ratings & ${[Link]('en-in')}
reviews`;

[Link]("price").innerHTML = [Link]('en-in',
{style:'currency', currency:'INR', minimumFractionDigits:0, maximumFractionDigits:0});

[Link](function(offer){

var li = [Link]("li");

[Link] = `<span class="text-secondary">${offer}</span>`;

[Link] = "bi bi-tag-fill my-3 text-success";

[Link]("offers").appendChild(li);

})

</script>

</head>

<body class="container-fluid p-4" onload="bodyload()">

<div class="row">

<div class="col-3">

<img id="imgProduct" width="100%">

</div>

<div class="col-9">

<div id="title" class="fs-4"></div>


<div class="mt-2">

<span class="badge bg-success text-white">

<span id="rating"></span> <span class="bi bi-star-fill"></span>

</span>

<span id="reviews" class="fw-bold text-secondary mx-2"></span>

</div>

<div class="mt-3">

<div id="price" class="fw-bold fs-2"></div>

</div>

<div class="mt-2">

<h5>Available Offers</h5>

<ul id="offers" class="list-unstyled">

</ul>

</div>

</div>

</div>

</body>

</html>
Page -16

Fetch and API

JavaScript Ajax

- XMLHttpRequest

Issues with XMLHttpRequest Object:

- It is not async implicitly.

- It requires explicit async to enable.

- It returns data in text or XML format.

- It requires explicit conversion of data.

- It is not good in error handling.

- CORS issues [ Cross Origin Resource Sharing ]

JavaScript Fetch Promise

- It uses XMLHttpRequest in browser window.

- Fetch is a promise and it is async.

- It is better in error handling.

- It returns data response in binary format.

- It requires explicit conversion.


- It is better in handling CORS.

Syntax:

fetch(“url”)

.then(function(response){

// convert and return response into required format.

})

.then(function(data){

// use the data

})

.catch(function(error){

// report error

})

.finally(function(){

// runs always - on success or on failure

})

Ex:

Data/[Link]

{
"title": "Apple iPhone 16 (Pink, 256 GB)",

"price": 79000,

"rating": {"rate":4.4, "ratings":154568, "reviews":206},

"image": "../public/images/[Link]",

"offers": [

"Bank Offer5% cashback on Axis Bank Flipkart Debit Card up to ₹750T&C",

"Bank Offer5% cashback on Flipkart SBI Credit Card upto ₹4,000 per calendar quarterT&C",

"Bank Offer5% cashback on Flipkart Axis Bank Credit Card upto ₹4,000 per statement quarterT&C",

"Bank OfferUp To ₹50 Cashback on BHIM Payments App. Min Order Value ₹199. Offer Valid Once Per
User"

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/[Link]">

<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/[Link]">


<script>

function bodyload(){

fetch('../data/[Link]')

.then(function(response){

return [Link]();

})

.then(function(product){

[Link]("imgProduct").src = [Link];

[Link]("title").textContent = [Link];

[Link]("rating").textContent = [Link];

[Link]("reviews").innerHTML = `
${[Link]('en-in')} ratings & ${[Link]('en-in')}
reviews`;

[Link]("price").innerHTML = [Link]('en-in',
{style:'currency', currency:'INR', minimumFractionDigits:0, maximumFractionDigits:0});

[Link](function(offer){

var li = [Link]("li");

[Link] = `<span class="text-secondary">${offer}</span>`;

[Link] = "bi bi-tag-fill my-3 text-success";

[Link]("offers").appendChild(li);

})
})

.catch(function(error){

[Link](error);

})

.finally(function(){

[Link]('Ajax Request Completed');

})

</script>

</head>

<body class="container-fluid p-4" onload="bodyload()">

<div class="row">

<div class="col-3">

<img id="imgProduct" width="100%">

</div>

<div class="col-9">

<div id="title" class="fs-4"></div>

<div class="mt-2">

<span class="badge bg-success text-white">

<span id="rating"></span> <span class="bi bi-star-fill"></span>

</span>
<span id="reviews" class="fw-bold text-secondary mx-2"></span>

</div>

<div class="mt-3">

<div id="price" class="fw-bold fs-2"></div>

</div>

<div class="mt-2">

<h5>Available Offers</h5>

<ul id="offers" class="list-unstyled">

</ul>

</div>

</div>

</div>

</body>

</html>

[] Array

{} Object

[{}] Array of Object

Ex:

1. Data/[Link]
[

"title": "Apple iPhone 16 (Pink, 256 GB)",

"price": 79000,

"rating": {"rate":4.4, "ratings":154568, "reviews":206},

"image": "../public/images/[Link]",

"features": [

"256 GB ROM",

"15.49 cm (6.1 inch) Super Retina XDR Display",

"48MP + 12MP | 12MP Front Camera",

"A18 Chip, 6 Core Processor Processor",

"1 year warranty for phone and 1 year warranty for in Box Accessories"

},

"title": "Apple iPhone 16 (White, 128 GB)",

"price": 69000,

"rating": {"rate":4.4, "ratings":154568, "reviews":206},

"image": "../public/images/[Link]",

"features": [
"126 GB ROM",

"15.49 cm (6.1 inch) Super Retina XDR Display",

"48MP + 12MP | 12MP Front Camera",

"A18 Chip, 6 Core Processor Processor",

"1 year warranty for phone and 1 year warranty for in Box Accessories."

2. [Link]

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/[Link]">

<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/[Link]">

<script>

function bodyload(){

fetch('../data/[Link]')
.then(function(response){

return [Link]();

})

.then(function(products){

[Link](function(product){

var tr = [Link]("tr");

var tdTitle = [Link]("td");

var tdImage = [Link]("td");

var tdFeatures = [Link]("td");

var tdPrice = [Link]("td");

var tdRatings = [Link]("td");

[Link] = [Link];

[Link] = `<img width="100" height="100" src=${[Link]}>`;

[Link]= [Link]('en-in', {style:'currency', currency:'INR'});

[Link] = `${[Link]} <span class="bi bi-star-fill text-success"></


span> <br> [${[Link]} ratings & ${[Link]} reviews]`;

var ul = [Link]("ul");

[Link](function(feature){

var li = [Link]("li");

[Link] = "10px";
[Link] = feature;

[Link](li);

})

[Link](ul);

[Link](tdTitle);

[Link](tdImage);

[Link](tdFeatures);

[Link](tdPrice);

[Link](tdRatings);

[Link]("tbody").appendChild(tr);

})

})

</script>

</head>

<body class="container-fluid" onload="bodyload()">

<h3>Products Table</h3>

<table class="table table-hover">


<thead>

<tr>

<th>Title</th>

<th>Preview</th>

<th width="300">Features</th>

<th>Price</th>

<th>Ratings</th>

</tr>

</thead>

<tbody>

</tbody>

</table>

</body>

</html>

Weather API

1. Visit the website

[Link]

2. Register a free account to get API key


3. Login into your account => Go to Profile => API Keys => Copy your API Key and store

somewhere on your PC text document.

1318ca6725c69160d346c41fc0612596

4. Go to API Menu in Nav => Select Current Weather Data => API DOC => By City Name

[Link] name}&appid={API key}

[Link]
q=Hyderabad&appid=1318ca6725c69160d346c41fc0612596

[Link]
q=Hyderabad&appid=1318ca6725c69160d346c41fc0612596&units=metric

AI Tool for Design Ideas : [Link]

- Create Weather App home page


- User can search by city name using textbox

- Weather Details must show temp, wind speed, humidity

Ex:

1. Src/scripts/[Link]

var cityName = "Hyderabad"

function SearchClick(){

cityName = [Link]("txtCity").value;

var api_url = `[Link]


&appid=1318ca6725c69160d346c41fc0612596&units=metric`;

fetch(api_url)

.then(function(response){

return [Link]();

})

.then(function(weatherObj){

[Link]("lblCity").innerHTML = cityName;

[Link]("lblTemp").innerHTML = `${[Link]}&deg;C`;
})

2. [Link]

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/[Link]">

<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/[Link]">

<script src="../src/scripts/[Link]"></script>

</head>

<body class="container-fluid bg-secondary d-flex justify-content-center align-items-center"


style="height:100vh">

<div class="bg-light p-4" style="height:300px; width:600px">

<div class="input-group">

<button onclick="SearchClick()" class="btn btn-warning bi bi-search"></button><input type="text"


placeholder="Search City Name" id="txtCity" class="form-control">

</div>

<div class="mt-2">
<span id="lblCity" class="fs-5 fw-bold"></span>

</div>

<div class="mt-3">

<span id="lblTemp" class="fs-1 fw-bold text-center"></span>

</div>

</div>

</body>

</html>

Page -17

Fakestore API

Weather API

- fetch()

- XMLHttpRequest

{} Object

[] Array

[ { }, { } ] Array of objects
Fakestore API

([Link]

API Routes / End Points

GET /products [{ }, { } ] of products

GET /products/1 { } specific product

GET /products/categories [ ‘ ’ ] all categories

GET /products/category/electronics [{ }, { }] products belong to specific category

URL: [Link]

Data

id : number,

title: string,

price: number,

description: string,

image:string,

category:string,
rating: {rate: number, count: number}

Ex:

1. Src/scripts/[Link]

function LoadCategories(){

fetch(`[Link]

.then(function(response){

return [Link]();

})

.then(function(categories){

[Link]("all");

[Link](function(category){

var option = [Link]("option");

[Link] = [Link]();

[Link] = category;

[Link]("lstCategories").appendChild(option);

})

})

}
function LoadProducts(url){

[Link]("main").innerHTML = "";

fetch(url)

.then(function(response){

return [Link]();

})

.then(function(products){

[Link](function(product){

var div = [Link]("div");

[Link] = "card m-2 p-2";

[Link] = "200px";

[Link] = `

<img src=${[Link]} class="card-img-top" height="120">

<div class="card-header overflow-auto" style="height:100px">

${[Link]}

</div>

<div class="card-body">

<dl>

<dt>Price</dt>

<dd>${[Link]}</dd>
<dt>Rating</dt>

<dd>${[Link]} <span class="bi bi-star-fill text-success"></span></dd>

</dl>

</div>

<div class="card-footer">

<button onclick="AddClick(${[Link]})" class="btn bi bi-cart4 btn-warning w-100"> Add to


Cart </button>

</div>

`;

[Link]("main").appendChild(div);

})

})

function bodyload(){

LoadCategories();

LoadProducts("[Link]

GetCartCount();

function CategoryChange(){

var categoryName = [Link]("lstCategories").value;


if(categoryName=="all"){

LoadProducts("[Link]

} else {

LoadProducts(`[Link]

function SearchClick(){

var searchString = [Link]("txtSearch").value;

LoadProducts(`[Link]

function SearchKeyUp(){

var searchString = [Link]("txtSearch").value;

var cards = [Link]("card");

for(var card of cards){

if([Link](searchString)){

[Link] = "block";

} else {

[Link] = "none";

}
}

var cartItems = [];

function GetCartCount(){

[Link]("lblCount").innerHTML = [Link];

function GetCartTotal(){

var total = 0;

for(var item of cartItems){

total+=[Link];

[Link]("lblTotal").innerHTML = `Total Cart Cost : <span class="fw-bold fs-4 text-


danger">${total}</span>`;

function AddClick(id){

fetch(`[Link]

.then(function(response){
return [Link]();

})

.then(function(product){

[Link](product);

alert(`${[Link]}\nAdded to Cart`);

GetCartCount();

GetCartTotal();

})

function ShowCartClick(){

[Link]("tbody").innerHTML = "";

[Link](function(item){

var tr = [Link]("tr");

var tdTitle = [Link]("td");

var tdImage = [Link]("td");

var tdPrice =[Link]("td");

[Link] = [Link];

[Link] = [Link];

[Link] = `<img width="50" height="50" src=${[Link]}>`;

[Link](tdTitle);
[Link](tdImage);

[Link](tdPrice);

[Link]("tbody").appendChild(tr);

})

GetCartTotal();

2. Js-examples/[Link]

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/[Link]">

<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/[Link]">

<script src="../node_modules/bootstrap/dist/js/[Link]"></script>

<script src="../src/scripts/[Link]"></script>

</head>

<body class="container-fluid" onload="bodyload()">

<header class="p-2 d-flex justify-content-between mt-2 bg-light">


<div class="fs-3 fw-bold">Shopping.</div>

<div>

<div class="input-group" style="width:400px">

<input type="text" id="txtSearch" onkeyup="SearchKeyUp()" placeholder="Search fakestore


categories" class="form-control">

<button onclick="SearchClick()" class="bi btn btn-warning bi-search"></button>

</div>

</div>

<div>

<button onclick="ShowCartClick()" data-bs-target="#cart" data-bs-toggle="offcanvas" class="btn


btn-warning bi bi-cart4 position-relative">

<span id="lblCount" class="badge bg-danger rounded rounded-circle text-white position-


absolute"></span>

</button>

<div class="offcanvas offcanvas-end" id="cart">

<div class="offcanvas-header">

<h3>Your Cart Items</h3>

<button class="btn btn-close" data-bs-dismiss="offcanvas"></button>

</div>

<div class="offcanvas-body">

<table class="table table-hover">

<thead>

<tr>
<th>Title</th>

<th>Preview</th>

<th>Price</th>

</tr>

</thead>

<tbody>

</tbody>

<tfoot>

<td align="right" colspan="3" id="lblTotal"></td>

</tfoot>

</table>

</div>

</div>

</div>

</header>

<section class="row">

<nav class="col-2">

<div class="my-3">

<label class="fw-bold form-label">Select Category</label>

<div>
<select onchange="CategoryChange()" id="lstCategories" class="form-select">

</select>

</div>

</div>

</nav>

<main class="col-10 d-flex flex-wrap flex-row overflow-auto" style="height:550px">

</main>

</section>

</body>

</html>

Page -18

Map, Date, Timer Events

- Array

- Object

Issues with Object:


- Key must be only string type. - It requires explicit methods for manipulation.

- It is slow in interactions.

Map Type

- It is a key and value collection same as object.

- Key can be any type and value can be any type.

- It provides various implicit methods for manipulation.

- It is faster than object.

- It is schema less [structure less]

Syntax:

let data = new Map();

[Link](key, value)

[Link](key)

[Link](key)

[Link]()

[Link]

[Link]()

[Link]()

[Link]()

[Link]()
Ex:

<script>

var data = new Map();

[Link](1, "TV");

[Link]("categories", ["Electronics", "Fashion"]);

[Link](1);

for(var item of [Link]()){

[Link](item + "<br>");

</script>

FAQ: What is difference between Object & Map?

Date Type

- Javascript provides a “Date()” constructor.

- It allocates memory to handle date and time values.

Syntax:

let now = new Date(); // loads current date and time


let dept = new Date(“year-month-day hours:min:[Link]”); // specific date & time

- Javascript provides various date and time methods to get and set date.

getHours() 0 to 23

getMinutes() 0 to 59

getSeconds() 0 to 59

getMilliSeconds() 0 to 999

getDate() 1 to 28, 29, 30, 31

getDay() 0 to 6 [0 = Sunday]

getMonth() 0 to 11 [0 = January]

getFullYear() 2025

toDateString()

toLocaleDateString()

toTimeString()

toLocaleTimeString() etc..

Note: You have to depend of 3rd party date libraries to display and manipulate dates.

[ moment, dayjs, luxon etc]

Ex:
<script>

var departure = new Date("2025-12-28 [Link].928");

var months = ["January", "Feb", "March", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov",
"December"];

var weekdays = ["Sunday", "Mon", "Tue", "Wed","Thu", "Friday", "Saturday"];

[Link](`${[Link]()} ${weekdays[[Link]()]},
${months[[Link]()]} ${[Link]()}`);

</script>

- JavaScript can set date and time by using setter methods

setHours()

setMinutes()

setSeconds()

setMilliSeconds()

setDate()

setMonth()

setFullYear()

Syntax:

var now = new Date();

[Link](15);

[Link](29);
Ex:

<script>

var now = new Date();

[Link](15);

var hrs = [Link]();

if(hrs>=0 && hrs<=12){

[Link]("Good Morning <br> <img src='../public/images/[Link]' width='100'


height='100'>");

} else if(hrs>12 && hrs<=16){

[Link]("Good Afternoon <br> <img src='../public/images/[Link]' width='100'


height='100'>");

} else {

[Link]("Good Evening");

</script>

Timer Events:

setTimeout()

clearTimeout()
setInterval()

clearInterval()

setTimeout()

- It is used to configure “debounce”.

- Bounce is a mechanism where the task is executed immediately.

- Debounce allows to delay the execution of task.

- It loads task into memory and keeps it inactive for specific duration of time.

Syntax:

setTimeout(function(){ }, interval);

clearTimeout()

- It is used to remove task from memory before released into process.

- It requires a reference name for task in memory.

Syntax:

let thread = setTimeout(function(){ }, interval);

clearTimeout(thread);

Ex:

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/[Link]">

<script>

function Level1(){

[Link]("p").innerHTML = "Volume Increased : 10%";

function Level2(){

[Link]("p").innerHTML = "Volume Increased : 60%";

function Level3(){

[Link]("p").innerHTML = "Volume Full";

let l1, l2, l3;

function VolumeIncrease(){

l1 = setTimeout(Level1, 4000);
l2 = setTimeout(Level2, 8000);

l3 = setTimeout(Level3, 15000);

function CancelClick(){

clearTimeout(l2);

</script>

</head>

<body>

<button onclick="VolumeIncrease()" class="bi bi-volume-up-fill"></button>

<button onclick="CancelClick()">Cancel L2</button>

<p></p>

</body>

</html>

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>
<script>

function Clock(){

var now = new Date();

var time = [Link]();

[Link]("h1").innerHTML = time;

function bodyload(){

setInterval(Clock,1000);

</script>

</head>

<body onload="bodyload()">

<h1 align="center"></h1>

</body>

</html>

Page-19

Operators

Debounce
- setTimeout()

- clearTimeout()

Throttle

- It is the process of executing specified task at regular intervals.

- It loads task into memory and releases a copy into process.

- You can throttle a function by using “setInterval()”.

- You can cancel by using “clearInterval()”.

Syntax:

setInterval(function(){}, interval);

clearInterval(reference_name);

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function Clock(){
var now = new Date();

var time = [Link]();

[Link]("h1").innerHTML = time;

function bodyload(){

setInterval(Clock,1000);

</script>

</head>

<body onload="bodyload()">

<h1 align="center"></h1>

</body>

</html>

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>
<style>

.container {

width: 600px;

display: grid;

grid-template-columns: 3fr 3fr 3fr 3fr;

padding: 20px;

background-color: rgb(199, 241, 255);

font-size: 50px;

font-family: Arial;

font-weight: bold;

text-align: center;

height: 70px;

button {

font-size: 20px;

padding: 10px;

background-color: lightblue;

border: none;

</style>

<script>

var ms = 0;
var sec = 0;

function StartClock(){

var hours = 0;

var min = 0;

ms++;

if(ms==999){

ms = 0;

sec++;

if(sec==59){

min++;

[Link]("ms").innerHTML = ms;

[Link]("sec").innerHTML = sec;

[Link]("min").innerHTML = min;

var thread;

function StartClick(){

thread = setInterval(StartClock,1);
}

function StopClick(){

clearInterval(thread);

</script>

</head>

<body>

<div class="container">

<div>

<span id="hours">00</span>

</div>

<div>

<span id="min">00</span>

</div>

<div>

<span id="sec">00</span>

</div>

<div>

<span id="ms">000</span>

</div>

</div>

<br><br>
<button onclick="StartClick()">Start</button>

<button onclick="StopClick()">Stop</button>

</body>

</html>

Summary Data Types

- Number

- String

- Boolean

- Null

- Undefined

- Symbol

- Bigint

- Array

- Object

- Map

- Date

- Regular Expression / /

Note: Primitive types use value and Non Primitive types use reference.
Ex:

<script>

var a = 10;

var b = a; // using value

b = 20;

[Link](`a=` + a + "<br>");

var user = {name:'sam'};

var admin = user; // using reference

[Link] = 'John';

[Link](`User Name : ${[Link]}`);

</script>

Javascript Operators

- Operator is an object that evaluates any value.

- Data is kept in operands.

- Logic is defined using entity.

a +b

a, b => operands

+ => entity
- Based on number of operands an operator can handle, they are categorized into

a) Unary Operator

b) Binary Operator

c) Ternary Operator

- Unary operator performs operation on only one operand.

++ increment

-- decrement

! not

Increment

- It increases the current value by 1 and assigns to same reference.

- You can post increment or pre increment a value.

POST Increment [X++]

- It assigns a value into reference and later increments

var x = 10;
var y = x++; x=11, y=10

Pre Increment [++X]

- It increments the current value and later assigns to reference.

var x = 10;

var y = ++x; x = 11, y = 11

Decrement

- It decreases the current value by 1 and assigns to reference.

- You can post or pre-decrement a value.

POST Decrement [X--]

var x = 10;

var y = x--; x=9, y=10

Pre Decrement [--X]

var x = 10;

var y = --x; x = 9, y=9


Ex:

1. Src/[Link]

function LoadProduct(id){

[Link]("txtRange").value=id;

fetch(`[Link]

.then(function(response){

return [Link]();

})

.then(function(product){

[Link]("lblTitle").innerHTML = [Link];

[Link]("imgProduct").src = [Link];

[Link]("lblPrice").innerHTML = [Link]('en-us',
{style:'currency', currency:'USD'});

})

let productId = 1;

function NextClick(){

productId++;

LoadProduct(productId);

}
function PreviousClick(){

productId--;

LoadProduct(productId);

function SliderChange(){

var sliderValue = parseInt([Link]("txtRange").value);

productId = sliderValue;

LoadProduct(productId);

function LoadProductAuto(){

productId++;

[Link]("txtRange").value=productId;

fetch(`[Link]

.then(function(response){

return [Link]();

})

.then(function(product){

[Link]("lblTitle").innerHTML = [Link];

[Link]("imgProduct").src = [Link];
[Link]("lblPrice").innerHTML = [Link]('en-us',
{style:'currency', currency:'USD'});

})

var thread;

function PlayClick(){

thread = setInterval(LoadProductAuto, 5000);

[Link]("lblStatus").innerHTML = "[Slide Show - Running]";

function PauseClick(){

clearInterval(thread);

[Link]("lblStatus").innerHTML = "[Slide Show - Paused]";

2. Js-examples/[Link]

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/[Link]">

<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/[Link]">

<script src="../src/scripts/[Link]"></script>

</head>

<body onload="LoadProduct(1)" class="container-fluid d-flex justify-content-center">

<div class="card p-2 mt-4" style="width: 600px;">

<div class="card-header text-center overflow-auto" style="height: 70px;">

<div id="lblTitle"></div>

<div class="fw-bold" id="lblStatus"></div>

</div>

<div class="card-body row">

<div class="col-1 d-flex flex-column justify-content-center align-items-center">

<button onclick="PreviousClick()" class="btn btn-dark bi bi-chevron-left"></button>

</div>

<div class="col-10 position-relative">

<img id="imgProduct" width="100%" height="300">

<div id="lblPrice" class="position-absolute p-3 fs-5 top-0 end-0 badge rounded rounded-circle
bg-danger text-white"></div>

<input type="range" onchange="SliderChange()" min="1" max="20" id="txtRange" class="form-


range">

</div>

<div class="col-1 d-flex flex-column justify-content-center align-items-center">


<button onclick="NextClick()" class="btn btn-dark bi bi-chevron-right"></button>

</div>

</div>

<div class="card-footer text-center">

<button onclick="PlayClick()" class="btn btn-warning bi bi-play"></button>

<button onclick="PauseClick()" class="btn btn-danger bi bi-pause mx-2"></button>

</div>

</div>

</body>

</html>

- Binary operators handle operations on 2 operands.

[ + , / , * ] etc.

- Ternary operator handles operation on 3 operands.

?:

Syntax:

(condition) ? True : False

if (condition)
{

true;

else

false;

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/[Link]">

<script>

function ButtonClick(){

[Link]("button").textContent =
([Link]("button").textContent=="Start")?"Stop":"Start";

function SortClick(){

var btnSort = [Link]("btnSort");


[Link] = ([Link]=="bi bi-sort-alpha-down")?"bi bi-sort-alpha-up":"bi bi-sort-
alpha-down";

</script>

</head>

<body>

<button onclick="ButtonClick()">Start</button>

<button onclick="SortClick()" id="btnSort" class="bi bi-sort-alpha-down"></button>

</body>

</html>

Page-20

Operators continue

JavaScript Operators

1. Unary

2. Binary

3. Ternary

4. Arithmetic Operators

+ Addition
- Subtraction

* Multiplication

/ Division

% Modulus Division

** Exponent [Power] 2**3 = 8 [ [Link](2,3) ]

++ Increment

-- Decrement

Ex:

1. Src/[Link]

function AmountChange(){

[Link]("txtAmount").value =

[Link]("rangeAmount").value;

function YearChange(){

[Link]("txtYears").value =

[Link]("rangeYears").value;

function RateChange(){
[Link]("txtRate").value =

[Link]("rangeRate").value;

function CalculateClick(){

var P = parseInt([Link]("txtAmount").value);

var r = parseFloat([Link]("txtRate").value)/12/100;

var n = parseInt([Link]("txtYears").value)*12;

var EMI = P * r * ([Link](1+r,n)) / ([Link](1+r,n))-1;

[Link]("lblResult").innerHTML = `${[Link]('en-in', {style:'currency',


currency:'INR', minimumFractionDigits:0, maximumFractionDigits:0})} for ${n} months`;

2. [Link]

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/[Link]">

<script src="../src/scripts/[Link]"></script>

</head>

<body class="container-fluid bg-light row">

<div class="col-8 p-2">

<div class="card p-4 w-100">

<div>

<div class="d-flex align-items-center justify-content-between">

<div>

<span class="fs-5 fw-bold">Loan Amount</span>

</div>

<div>

<input type="text" id="txtAmount" class="form-control">

</div>

</div>

<div class="my-2">

<input type="range" onchange="AmountChange()" step="10000" min="100000" max="1000000"


value="100000" class="form-range" id="rangeAmount">

<div>

<span>&#8377; 1,00,000/-</span>

<span class="float-end">&#8377; 10,00,000/-</span>

</div>
</div>

</div>

<div class="mt-3">

<div class="d-flex align-items-center justify-content-between">

<div>

<span class="fs-5 fw-bold">Loan Tenure</span>

</div>

<div>

<input type="text" size="3" id="txtYears" class="form-control">

</div>

</div>

<div class="my-2">

<input type="range" onchange="YearChange()" min="1" max="5" value="1" class="form-range"


id="rangeYears">

<div>

<span>1 Year</span>

<span class="float-end">5 Years</span>

</div>

</div>

</div>
<div class="mt-3">

<div class="d-flex align-items-center justify-content-between">

<div>

<span class="fs-5 fw-bold">Interest Rate</span>

</div>

<div>

<input type="text" size="4" id="txtRate" class="form-control">

</div>

</div>

<div class="my-2">

<input type="range" onchange="RateChange()" min="10.45" max="24.45" value="10.45"


step="0.01" class="form-range" id="rangeRate">

<div>

<span>10%</span>

<span class="float-end">24%</span>

</div>

</div>

</div>

<div class="text-center">

<button onclick="CalculateClick()" class="btn btn-primary w-25 mt-4">Calculate</button>

</div>

</div>
</div>

<div class="col-4 p-2">

<div class="card p-4 w-100">

<div class="h1">Installment Amount</div>

<div class="mt-4">

<span id="lblResult" class="h4"></span>

</div>

</div>

</div>

</body>

</html>

Task: Design BMI calculator

5. Comparison Operators

== Equal

=== Identical Equal / Strict Equal

!= Not Equal

!== Not Identical

> Greater than >= Greater than or equal to


< Less than

<= Less than or equal to

FAQ: What is difference between “==“ and “===“ ?

Ans : “==“ can compare values of different data types.

“===“ will compare only values of same data type.

“10” == 10 // true

“10” === 10 // false

“10” === “10” // true

6. Logical Operators

&& AND

|| OR

! Not

expression-1 && expression-2 => returns true only when both expressions are true

returns false if any one expression is false.

expression-1 || expression-2 => returns true if any one expression is true.


returns false if all expressions are false.

!true => false

!undefined => defined

!null => have value

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

var user = {

user_name: "john_nit",

password: "john@123",

email: "john@[Link]"

function LoginClick(){

var username = [Link]("txtName").value;

var password = [Link]("txtPwd").value;


if((username===user.user_name || username===[Link]) && password===[Link]){

[Link]("Login Success..");

} else {

alert("Invalid Credentials");

</script>

</head>

<body>

<dl>

<dt>User Name / Email</dt>

<dd><input type="text" id="txtName"></dd>

<dt>Password</dt>

<dd><input type="password" id="txtPwd"></dd>

</dl>

<button onclick="LoginClick()">Login</button>

</body>

</html>

7. Assignment Operators
+= Add and assign

-= Subtract and assign

*= Multiply and assign

/= Divide and assign

%= Modulus and assign

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function SubmitClick(){

var courseName = "";

var checkboxes = [Link]("course");

for(var checkbox of checkboxes){

if([Link]){

courseName += [Link] + "<br>";

}
[Link]("p").innerHTML = courseName;

</script>

</head>

<body>

<ul>

<li><input type="checkbox" value="Java" name="course"> Java </li>

<li><input type="checkbox" value="React" name="course"> React </li>

<li><input type="checkbox" value=".NET" name="course"> .NET </li>

<li><input type="checkbox" value="Angular" name="course"> Angular </li>

</ul>

<button onclick="SubmitClick()">Submit</button>

<h3>Selected Courses</h3>

<p></p>

</body>

</html>

Ex:

<!DOCTYPE html>

<html lang="en">

<head>
<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

var position = 1;

function MoveRight(){

position *= 2;

var img = [Link]("img");

[Link] = position + "px";

function MoveLeft(){

position /= 2;

var img = [Link]("img");

[Link] = position + "px";

</script>

</head>

<body>

<button onclick="MoveLeft()"> < </button>

<button onclick="MoveRight()"> > </button>

<br><br>

<img src="../public/images/[Link]" width="100" height="100">


</body>

</html>

Task:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

var data = [

{ Name: 'Java', Fee: 4500},

{ Name: 'React', Fee: 7000},

{ Name: '.NET', Fee: 5000}

</script>

</head>

<body>

<ul>

// Course Names as <li value="7000"> React </li>


</ul>

<button>Submit</button>

<p>Course Names</p>

<p>Total Amount</p>

</body>

</html>

Page-21

Statements

Javascript Special Operators

1. Ternary Operator “?:”

- It is used in decision making.

- It uses a condition and defines statements to execute on true or false.

Syntax:

(condition) ? True : False

2. new

- It is dynamic memory allocation operator.


Syntax:

let data = new Array();

let mfd = new Date();

3. delete

- It is used to delete a key from object.

Syntax:

delete [Link];

4. in

- It is used to verify a key in object.

- It returns true if key exists.

Syntax:

“key” in object => true / false

5. typeof

- It returns the data type of value stored in a reference.


Syntax:

var x = “John”;

typeof x ; // string

6. instanceOf

- It returns true if object is derived from specified class.

Syntax:

object instanceOf className; // true or false

7. void

- It discards the return of any element or function.

- It specifies that element or function will not return anything.

Syntax:

<a href=“javascript:void()”> Home </a>

8. yield

- It yields the result of an iterator.

- It is used by function generator.

Syntax:
yield value;

Javascript Statements

- Statements are use to control the execution flow in a program.

- Statements are categorized into following groups

1. Selection Statements

if, else, switch, case, default

2. Looping Statements

for, while, do while

3. Iteration Statements

for..in, for..of

4. Jump Statements

break, return, continue

5. Exception Handling Statements try, catch, throw, finally


Selection Statements

- Selection statements are used in decision making.

IF Selector:

- It is a decision making approach where a set of statements are executed

based on the boolean expression or value.

- It have multiple forms

a) Forward Jump

b) Simple Decision

c) Multilevel Decisions

d) Multiple Choices

Forward Jump

- It is a decision making approach where statements are executed only when condition
evaluates to true.

- It will not provide any alternative.

Syntax:

if (booleanExpression | value )
{

statements;

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

var user = {

Card: "4444555566667890",

Cvv: "2345",

Expiry: "2026"

function VerifyCard(){

var card = [Link]("txtCard").value;

if(card===[Link]){

[Link]("txtCvv").disabled = false;

}
}

</script>

</head>

<body>

<h3>Payment Details</h3>

<dl>

<dt>Your Card</dt>

<dd><input type="text" onblur="VerifyCard()" id="txtCard"></dd>

<dt>Cvv</dt>

<dd><input type="text" disabled id="txtCvv" size="4"></dd>

<dt>Expiry</dt>

<dd>

<select disabled id="lstExpiry">

<option>Select Expiry</option>

<option>2024</option>

<option>2025</option>

<option>2026</option>

</select>

</dd>

</dl>

<button disabled>Pay</button>
</body>

</html>

Simple Decision:

- It is a decision making approach that provides one alternative to execute when

condition evaluates to false.

- It uses “IF” with “Else” clause.

Syntax:

if (condition )

statement on true;

else

statement on false;

Multi Level Decisions:

- It is decision making approach used for multiple conditions.

- If there are multiple conditions and every condition must be satisfied, then
better to use multilevel approach.

- It uses forward only technique with individual alternative for every condition.

Syntax:

if (condition1)

if(condition2)

// statement on all conditions true

else

// statement on condition 2 false

else

// statement on condition-1 false;

Ex:

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

var user = {

user_name: "john_nit",

password: "john@123",

function LoginClick(){

var username = [Link]("txtName").value;

var password = [Link]("txtPwd").value;

if([Link]===0){

alert("User Name Required");

} else {

if(user.user_name===username){

if([Link]===password){

[Link]("Success..");

} else {

alert("Invalid Password");

}
} else {

alert("Invalid User Name");

</script>

</head>

<body>

<dl>

<dt>User Name</dt>

<dd><input type="text" id="txtName"></dd>

<dt>Password</dt>

<dd><input type="password" id="txtPwd"></dd>

</dl>

<button onclick="LoginClick()">Login</button>

</body>

</html>

Multiple Choices:

- It is decision making approach used to configure multiple conditions, where

any one condition can be true to satisfy the expression.


- It allows to choose any one from a group of choices.

Syntax:

if(condition1)

// statements on condition-1

else if(condition2)

// statements on condition-2

else

// statements when all conditions are false.

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/[Link]">

<script>

var user = {

mobile: "+919876543211",

email: "john@[Link]",

password: "john11"

var flag = "";

function ToggleContainers(){

[Link]("loginContainer").[Link] = "none";

[Link]("pwdContainer").[Link] = "block";

function ContinueClick(){

var userid = [Link]("txtUser").value;

var lblUserError = [Link]("lblUserError");

if(userid===[Link]){

flag = `Your mobile ${userid} verified - OTP sent successfully`;

ToggleContainers();

} else if(userid===[Link]){

flag = `Your email ${userid} verified - Link sent to Email`;

ToggleContainers();
} else {

[Link]= `${userid} doesn't exist`;

function LoginClick(){

var password = [Link]("txtPwd").value;

if(password===[Link]){

[Link](`<h1>${flag}</h1>`);

} else {

[Link]("lblPwdError").innerHTML = `Invalid Password`;

</script>

</head>

<body class="container-fluid d-flex justify-content-center">

<div class="mt-4">

<h3>Sign in or Create account</h3>

<div id="loginContainer">

<label class="form-label fw-bold">Your mobile number or email</label>

<div>

<input type="text" id="txtUser" class="form-control">

<div id="lblUserError" class="text-danger"></div>


</div>

<button onclick="ContinueClick()" class="btn btn-warning w-100 mt-3">Continue</button>

</div>

<div id="pwdContainer" style="display: none;">

<label class="form-label fw-bold">Your Password</label>

<div>

<input type="password" id="txtPwd" class="form-control">

<div id="lblPwdError" class="text-danger"></div>

</div>

<button onclick="LoginClick()" class="btn btn-warning w-100 mt-3">Login</button>

</div>

</div>

</body>

</html>

Page-22

Switch Selector

Selection Statements

- If statements

a) Forward Jump
b) Simple Decision

c) Multilevel

d) Multiple Choices

FAQ: What is issue with “else-if” statement?

Ans: If multiple conditions are configured then it verifies all conditions until it matches

the required. It will increase the compiling and processing time. It is slow.

Switch Statement

- Switch is a selector that selects exactly the matching case.

- It executes only the required block of statements.

- It is faster in interactions when configured with multiple conditions.

Syntax:

switch(value | expression)

case value | expression:

statements;

jump;

default:
statements;

jump;

Debug Process:

- Open Browser Developer Tools

[ right click in browser => inspect ]

- Go to “Sources” category

- Select your HTML page.

- Click on Line Number in code area to set a “Break Point”.

- Reload and run page.

- Compiler / Interpreter pauses at break point.

- Press F10 to move to next step. [ Use Next button ]

Ex:

<script>

var n = parseInt(prompt("Enter Number"));

switch(n)

case 1:

[Link]("One");

break;
case 2:

[Link]("Two");

break;

case 3:

[Link]("Three");

break;

case 4:

[Link]("Four");

break;

default:

[Link]("Please enter 1 to 4 only");

break;

</script>

FAQ’s:

1. Can we use “return” as jump statement in switch?

A. Yes

2. What is difference between “break” & “return”?

A. “break" will exit the block but it is continued with compiling the script.
“return” will exit the block and terminates the compiling. It can be used in a function.

3. Can we use case without break?

A. Yes. Break is not mandatory. If not defined then it stops at the end of switch.

4. Can we use switch without default?

A. Yes. If default is not defined then there is no alternative to display.

5. Can we use default before or between cases?

A. Yes. There is no order for case and default.

6. How to configure a set of statements or a block to execute on multiple

cases? Same block must execute for different cases.

A. By defining a continuous set of cases for same block.

case 1:

case 2:

statements;

jump;

Ex:
<script>

var choice = prompt("Enter Choice","Color Name | Pattern");

switch([Link]())

case "red":

case "green":

case "blue":

[Link]("You selected Color");

break;

case "lines":

case "dots":

case "strips":

[Link]("You selected pattern");

break;

default:

[Link]("Please enter color name or pattern name");

break;

</script>
Ex:

<script>

var choice = prompt("Enter Choice","Y/N");

switch(choice)

case "y":

case "Y":

[Link]("You selected Yes");

break;

case "n":

case "N":

[Link]("You selected No");

break;

default:

[Link]("Please enter y or n");

break;

</script>

7. How to configure same block to execute for a range of values?

A. Range can be verified using a boolean expression with “&&” operator.


If case is using boolean expressions then switch must always use “true” a value.

Syntax:

switch(true)

case condition:

statements;

jump;

Ex:

<script>

var n = parseInt(prompt("Enter number"));

switch(true)

case (n>=1 && n<=10):

[Link](`Your number ${n} is between 1 to 10`);

break;

case (n>=11 && n<=20):

[Link](`Your number ${n} is between 11 to 20`);

break;
}

</script>

Programs:

1. Write a function to find greatest among 2 numbers?

function FindGreatest(a, b)

// logic

FindGreatest(40, 20); O/p:

a=40 is greater than b=20

2. Write a function to find greatest among 3 number?

function FindGreatest(a, b, c)

}
O/P:

FindGreatest(20,10, 30)

C = 30 is greater than a=20 & b=10

Ex:

<script>

function FindGreatest(a,b,c){

if(a>b && a>c){

[Link](`a=${a} is greater than b=${b} & c=${c}`);

else if(b>c){

[Link](`b=${b} is greater than a=${a} & c=${c}`);

} else {

[Link](`c=${c} is greater than a=${a} & b=${b}`);

FindGreatest(10, 20, 40);

[Link]("<br>");

FindGreatest(30, 10, 20);

</script>
Page-23

Loops

Looping Control Statements

1. The “for” loop

- looping is the process of executing a set of statements repeatedly.

- It developer knows the exact number of iterations and iteration counter

will not change dynamically then better to use “for” loop.

Syntax:

for(initializer; condition; counter)

- Initializer defines a reference to start with.

var i=1

- Condition specifies the expression to stop

i<condition

- Counter specifies how to proceed, you can increment, decrement, step etc

Ex:
<script>

var data = [10, 20, 30, 40];

for(var i=0; i<[Link];i++)

[Link](data[i] + "<br>");

</script>

Ex:

<script>

function PrintTable(n){ // 5

for(var i=1; i<=10; i++)

[Link](`${n} x ${i} = ${n*i}<br>`);

PrintTable(parseInt(prompt("Enter Number")));

</script>

Ex:

<!DOCTYPE html>

<html lang="en">
<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function bodyload(){

var data = [

{Category: "Electronics", Products: ["TV", "Mobile"]},

{Category: "Fashion", Products: ["Jeans", "Shoes", "Shirts"]}

];

[Link](function(item){

var li = [Link]("li");

[Link] = [Link];

var ul = [Link]("ul");

[Link](function(product){

var ul_li = [Link]("li");

ul_li.innerHTML = product;

[Link](ul_li);

[Link](ul);

[Link]("ol").appendChild(li);
})

})

</script>

</head>

<body onload="bodyload()">

<ol>

</ol>

</body>

</html>

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function bodyload(){
var data = [

{Category: "Electronics", Products: ["TV", "Mobile"]},

{Category: "Fashion", Products: ["Jeans", "Shoes", "Shirts"]}

];

for(var i=0; i<[Link]; i++)

var li = [Link]("li");

[Link] = data[i].Category;

var ul = [Link]("ul");

for(j=0; j<data[i].[Link]; j++)

var ul_li = [Link]("li");

ul_li.innerHTML = data[i].Products[j];

[Link](ul_li);

[Link](ul);

[Link]("ol").appendChild(li);

}
</script>

</head>

<body onload="bodyload()">

<ol>

</ol>

</body>

</html>

Ex:

<script>

function PrintTriangle(n)

for(i=1;i<=n; i++)

for(j=1; j<=i; j++){

[Link]("*&nbsp;&nbsp;");

[Link]("<br>");

PrintTriangle(parseInt(prompt("Enter Number")));
</script>

Ex:

<script>

function PrintTriangle(n)

for(i=n;i>=1; i--)

for(j=1; j<=i; j++){

[Link]("*&nbsp;&nbsp;");

[Link]("<br>");

PrintTriangle(parseInt(prompt("Enter Number")));

</script>

2. While Loop

- It is a looping control statements used by developer when not sure about

number of iterations and iteration counter may change dynamically.

- It can execute statements only when given condition evaluates to true.


Syntax:

while(condition)

counter;

statements;

Ex:

<script>

var i = 1;

while(i<=10)

[Link](i + "<br>");

i++;

</script>

3. Do while

- It is similar to while but ensures that statements will execute at least once even when condition
evaluates to false.
Syntax:

do {

statements;

counter;

} while (condition);

<script>

var i = 1;

do {

[Link](i + "<br>");

i++;

} while(i<=10);

</script>

Task: Design a Pin verification screen

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>
<script>

function DisablePin(){

[Link]("pin").disabled = false;

function VerifyClick(){

var pin = [Link]("pin").value;

if(pin==="4567"){

[Link]("Success..");

}else{

[Link]("pin").disabled = true;

[Link]("p").innerHTML = "Pin Disabled for 10 sec";

setTimeout(DisablePin,10000);

</script>

</head>

<body>

Your PIN :

<input type="text" id="pin">

<button onclick="VerifyClick()">Verify</button>

<p></p>
</body>

</html>

Page-24

Functions

Jump Statements

a) break

b) return

c) continue

- “break” terminates the block, but keeps the compiling ON.

- “return” terminates the block and compiling.

- “continue” skips the current counter and continue to next.

Ex:

Data/[Link]

"user_id": "john"
},

"user_id": "john12"

},

"user_id": "john_nit"

},

"user_id": "david"

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>
function VerifyUser(){

var userid = [Link]("userid").value;

var lblMsg = [Link]("lblMsg");

fetch('../data/[Link]')

.then(function(response){

return [Link]();

})

.then(function(users){

for(var user of users){

if(user.user_id===userid){

[Link] = "User Id Taken - Try Another".fontcolor('red');

break;

} else {

[Link] = "User Id Available".fontcolor('green');

})

</script>

</head>

<body>
<h3>Register</h3>

<dl>

<dt>User Id</dt>

<dd><input type="text" onkeyup="VerifyUser()" id="userid"></dd>

<dd id="lblMsg"></dd>

</dl>

</body>

</html>

Ex:

<script>

for(var i=1; i<=10; i++){

if(i===5 || i===8)

continue;

[Link](i + "<br>");

}
</script>

Ex:

<script>

fetch('[Link]

.then(function(response){

return [Link]();

})

.then(function(products){

for(var product of products)

if([Link]==="jewelery" || [Link]==="electronics") {

continue;

[Link](`${[Link]} - <b>${[Link]}</b><br>`);

})

</script>

Exception Handling Statements:

- Exception handling is required to avoid abnormal termination of application.

- A program can return 2 types of errors


a) Compile Time

b) Run Time

- Compile time errors are syntactical errors due to which a program fails to

run.

- Run time errors occur while using application. Compiler can’t understand

the instructions provides and may terminate the application.

- You can prevent abnormal termination by using exception handling statements

a) try It is monitoring block, contains statements to execute.

b) catch It is handler block, reports the issues.

c) throw Throws exception explicitly

d) finally It executes always.

Syntax:

try

//statements to execute;

if(condition) {

throw “error message”;

catch(error) {
// report error

finally

// execute always

Ex:

<script>

try {

var a = parseInt(prompt("Enter A"));

var b = parseInt(prompt("Enter B"));

if(b===0){

throw "Can't Divide by Zero";

if(b>a){

throw "Can't divide by larger number";

var c = a / b;

[Link](`Division=${c}<br>`);

catch(error)
{

[Link](error + "<br>")

finally {

[Link]("Program End");

</script>

Summary

- Selection Statements

- Jump Statements

- Looping and Iteration Statements

- Exception Handling Statements

Javascript Functions

- Function is used to “refactor” the code.

- Refactoring is the process of extracting a set of statements and storing in

a code block with reference name. So that you can reuse the code without

rewriting.

- A function enables features like

a) reusability
b) extensibility

c) maintainability

d) testability etc.

Configuring Function

- A function can be configured using 2 techniques

a) Declaration

b) Expression

Syntax: Declaration

function Name()

Syntax: Expression

const Name = function() {

- Declaration allows hoisting of function, you can declare at any location and

access from any another location. It doesn’t require any order of accessibility.
- Expression will not allow hoisting even when configured with “var” keyword.

You have to declare and use the function.

- Expression allows to assign a new functionality according to situation.

Ex:

<script>

var result;

var password = prompt("Enter Password");

if(password==="admin"){

result = function(){

[Link]("Success..");

} else {

result = function(){

[Link]("Invalid Password");

result();

</script>
- Every function declaration have 3 parts

a) Declaration

b) Signature

c) Definition

function Name(params) => Declaration

Name(params) => Signature

{} => Definition

- Declaration configures the behaviour of function.

- Signature is used to access the function.

- Definition specifies the actions performed by function.

Function Parameters

- Parameters are required to modify a function.

- Function without parameters performs the same actions every time.

- Parameter can modify the action.

Syntax:

function Name(param)

{
}

Name(value);

- Parameter defined in declaration is known as “Formal Parameter”.

- Parameter defined in function call is known as “Actual Parameter”.

Formal Parameter = Actual Parameter;

param = value;

Ex:

<script>

function PrintNumbers(howMany){

for(var i=1; i<=howMany; i++){

[Link](i + "<br>");

PrintNumbers(5);

PrintNumbers(10);

</script>

Page-25
Function Params and Return

- Function Declaration

- Function Expression

- Function Definition

- Function Parameters

- Parameters are of 2 types

a) Formal Parameter

b) Actual Parameter

- A formal parameter is defined in function declaration. It is a reference name to store

value.

function Name(params) => params is formal parameter

- Actual parameter is the value passed while calling the function.

Name(value) => value is actual parameter

Formal Parameter = Actual Parameter

params = value
- Parameter can handle any type of data

a) Primitive

b) Non Primitive

c) Function

- If a function is configured with a parameter that returns function then it known as

Higher Order Function.

Ex:

<script>

function Demo(data)

[Link](function(item){

[Link]([Link] + "<br>");

})

Demo([{Name:'TV'}, {Name:'Mobile'}]);

</script>

Ex:
<script>

function Demo(action)

action();

Demo(function(){

[Link]("Higer Order Function")

})

</script>

- A function can have multiple parameters.

- Every parameter is a required parameter and has order dependency.

- If you want to skip any parameter then it requires to configure with “undefined”.

Ex:

<script>

function Product(id, name, price){

if(name){

[Link](`Id=${id}<br>Name=${name}<br>Price=${price}`);

} else {

[Link](`Id=${id}<br>Price=${price}`);

}
}

Product(1, undefined, 56000);

</script>

- ES6 provides default parameters, If actual is configured as “undefined” then function

uses the default value.

Syntax:

function Name(params=value)

Name(undefined)

Ex:

<script>

function Product(id, name="TV", price){

if(name){

[Link](`Id=${id}<br>Name=${name}<br>Price=${price}`);

} else {

[Link](`Id=${id}<br>Price=${price}`);
}

Product(1, "", 56000);

</script>

- A function can have max 65535 params on a 64bit memory device. - Too many parameters will
cause Injection Attacks.

- ES5+ versions provide “Rest” parameter.

- A single rest parameter can handle multiple actual values.

- A rest parameter is configured with “…” and parameter name.

- It is an array type that handles multiple elements.

Syntax:

function Name(…params)

Name(val1, val2, val3..)

- Every function can have only one rest parameter.

- You can use rest parameter with other parameters, but it must be last in formal list.

[Rest parameter must be last parameter]


EX:

<script>

function Product(title, ...data)

var [id, name, price] = data;

[Link](`<h1>${title}</h1>Id=${id}<br>Name=${name}<br>Price=${price}`);

Product("Product Details",1, "TV", 45000);

</script>

- Function supports spread operator to spread values of one argument into multiple

parameters.

Ex:

<script>

function Product(id, name, price)

[Link](`Id=${id}<br>Name=${name}<br>Price=${price}`);

var data = [1, "Mobile", 11300];

Product(...data);

</script>
FAQ: What is difference between rest and spread?

Ans: Rest is single formal parameters that handle multiple arguments.

Spread is one argument that spreads values into multiple parameters.

Rest : Formal

Spread : Actual

Function with Return:

- Return is a jump statement.

- It keeps the memory of a function alive even after it completes the actions defined.

- Function memory is used to handle function data.

Syntax:

function Name()

return value;

Name() = value;
Ex:

<script>

function Addition(a, b)

return a + b;

function Result(){

[Link](`Addition=${Addition(40,20)}`);

Result();

</script>

- A function can return any type of data.

a) Primitive

b) Non Primitive

c) Function

- If a function returns another function and stores in memory then it is known as

“Function Currying”.

Syntax:

function Name()
{

return function() { }

Name()();

Ex:

<script>

function Demo(){

return function(){

return function(){

[Link]("Function Currying");

Demo()()();

</script>

- If a function returns different value even when the function actions and parameters are

same then it is know as “Impure Function”.

Ex:
<script>

var count = 1;

function Demo(n){

return count+=n;

[Link](Demo(5) + "<br>");

[Link](Demo(5) + "<br>");

[Link](Demo(5) + "<br>");

</script>

- If a function returns the same value even when it is configured with different parameters

then it is known as “Pure Function”.

Ex:

<script>

function Demo(n){

n = 10;

return n;

[Link](Demo(5) + "<br>");

[Link](Demo(10) + "<br>");

[Link](Demo(15) + "<br>");
</script>

- A function can be configured with multiple return, which is used to return different values

based on a condition.

Syntax:

function Name()

if(condition)

return A;

else {

return B;

Ex:

<script>

function Demo(n){

if(isNaN(n)){
return [Link]();

} else {

return ++n;

[Link](Demo(prompt("Enter Value")));

</script>

Page-26

Functions continued

Function Parameters

Function Return

Pure and Impure

Higher Order

Function Currying

Function Closure

- Closure is a mechanism where outer function members are accessible to

inner function, but inner function members are not accessible to outer.

Ex:

<script>
function Outer(){

var x = 10;

function Inner(){

var y = 20;

return x + y;

[Link]("Addition=" + Inner());

Outer();

</script>

Function Chaining

- Chaining is the process of allowing a function to extend the functonality.

- You can invoke a function with reference of another function.

- Invoking function have no order dependency as they are in heap memory.

- It requires a function return object.

- Object can add members to reference memory using “this” keyword.

Syntax:

function Name()

{
return {

f1() {

return this;

},

f2() {

return this;

Name().f1().f2()

Name().f2().f1()

Name().f2()

Ex:

<script>

function Demo()

return {

A(){

[Link]("A");

return this;

},

B(){
[Link]("B");

return this;

},

C(){

[Link]("C");

return this;

Demo().A().C();

Demo().C().B();

Demo().A();

Demo().A().C().B();

</script>

Function Recursion

- Function recursion is the mechanism of calling a function with in the

context of same function.

- It is used to create indefinite loops.

- Developers mostly use to handle complex calculations and batch operations.


Syntax:

function f1()

f1();

f1();

Ex:

<script>

function f1()

[Link]("Hello !");

setTimeout(f1,3000);

f1();

</script>

Ex:

<script>

function Factorial(n){

if(n===1){
return 1;

} else {

return n * Factorial(n-1);

[Link](`Factorial of 6 is ${Factorial(6)}`);

</script>

Anonymous Function

- A function without name is known as anonymous function.

- Anonymous are used in expression or callbacks.

- Callback is a technique where function executes implicitly according to

state and situation.

- Anonymous function is executed using IIFE pattern.

[Immediately Invoking Function Expression]

Syntax:

(function(){ })();

Ex:

<script>
(function(){

[Link]("Anonymous");

})(); // IIFE

</script>

Function Promise

- Function is synchronous in operations.

- It uses a blocking technique.

- Promise is used to make it asynchronous.

- Asynchronous uses unblocking technique, where it can perform the given

task without blocking the other requests.

- Promise has 2 phases

a) Resolve

b) Reject

- Resolve is on success.

- Reject is on failure.

Syntax:

const demo = new Promise(function(resolve, reject){

if(condition) {

resolve();

} else {
reject();

})

demo().then().catch().finally()

- then() uses a callback on success

- catch() uses a callback on failure.

- finally() uses a callback to run always.

Ex:

<script>

const Getdata = new Promise(function(resolve, reject){

var url = prompt("Enter URL");

if(url==="[Link]"){

resolve([{Name:'TV'}, {Name:'Mobile'}]);

} else {

reject('Unable to Fetch Data - Invalid URL');

})

[Link](function(response){

[Link](response);
})

.catch(function(error){

[Link](error);

})

.finally(function(){

[Link]("Request End");

})

</script>

Async Functions

- Async is used to execute function without blocking.

- It uses “await” to run the given task in background.

- The advanced version of async and await is Promise.

Syntax:

async function Name()

return await value;

Name().then().catch().finally()
Ex:

<script>

async function GetData()

return await [{Name:'TV'}, {Name:'Mobile'}];

GetData().then(function(response){

[Link](response);

})

.catch(function(error){

[Link](error);

})

.finally(function(){

[Link]('End');

})

</script>

Function Generator

- Generator is used to create iterator.

- Iterator uses a generator pattern to read elements from a collection

in sequential order.
- It implicitly yields value and moves to next.

- It verify “done” and stops when true.

- It executes zero or multiple times using “*” meta character.

Syntax:

function* Generator()

Ex:

<script>

function* GetData(){

yield 10;

yield "A";

yield ["Delhi", "Hyd"];

const data = GetData();

[Link]([Link]())

[Link]([Link]())

[Link]([Link]())

[Link]([Link]())

</script>
Page -27

Events
Sudhakar Sharma (Sudhakar Sharma Naresh IT)•7 Jan
Arrow Functions

- It is a short hand technique of writing a function expression.

() for function and parameters

=> for return

=> { } for definition

- You can minify the code. Minification reduces the file size.

Syntax: without arrow

const hello = function(uname) {

return `Hello ! ${uname}`

Syntax: arrow method

const hello = (uname) => `Hello ! ${uname}`;


const hello = uname => `Hello ! ${uname}`;

Syntax:

const add = function(a,b) {

return a + b;

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

Syntax:

const print = function() {

[Link](“statement-1”);

[Link](“statement-2”);

const print = ( ) => {

// statements

- Arrow is used for anonymous functions mostly in callbacks.

Syntax:
[Link](item=> {

[Link](item);

})

Ex:

<script>

fetch('[Link]

.then(response=>[Link]())

.then(products=> {

[Link]((product,index)=> {

[Link](`[${index}]${[Link]}<br>`);

})

})

</script>

Javascript Events

- Event is a message sent by sender to its subscriber in order to notify change.

- It follows a software design pattern called “Observer”.

- It uses a delegate mechanism, which is function pointer mechanism.

function InsertClick() { } => subscriber


onclick=“InsertClick()” => sender

- Subscriber defines the actions to perform.

- Sender notifies the subscriber.

Event Handler

- Event is configured for any element in design using a handler.

click : is event name

on : is a handler name

<button onclick=“f1()”>

- “onclick” is an event handler.

Event Listener

- Event is configured for any element dynamically using a listener.

- You can attach any event to element by using the method

“addEventListener()”
Syntax:

[Link](“button”).addEventListener(“event”, ()=> {

})

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function bodyload(){

var button = [Link]("button");

[Link] = "Insert";

[Link]("click",()=>{

[Link]("Record Inserted");

})

[Link]("body").appendChild(button);
[Link]("btnDelete").addEventListener("click",function(){

[Link]("Record Deleted");

})

</script>

</head>

<body onload="bodyload()">

<button id="btnDelete">Delete</button>

</body>

</html>

Event Arguments

- Arguments are used to carry the payload.

- Payload refers to data carried from one location to another.

- Event can have 2 default arguments

a) this

b) event

- “this” is a keyword that sends information about current element, which

includes id, name, value, className, width, height, src, href etc.

- “event” is a keyword that sends information about current event, which

includes clientX, clientY, keyCode, charCode, which, ctrlKey, shiftKey etc.


Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function Database(element, e){

switch([Link]){

case "Insert":

[Link]("Record Inserted");

break;

case "Delete":

[Link]("Record Deleted");

break;

case "Update":

[Link]("Record Updated");

}
</script>

</head>

<body>

<button onclick="Database(this, event)" id="btnDelete" value="Delete">Delete</button>

<button onclick="Database(this, event)" id="btnInsert" value="Insert">Insert</button>

<button onclick="Database(this, event)" id="btnUpdate" value="Update">Update</button>

</body>

</html>

- You can send custom arguments along with default arguments.

- You can send only custom arguments if required.

- You can use both spread and rest approach to handle parameters.

Syntax:

<button onclick=“Details(param1, param2)”>

function Details(…params) { }

function Details(p1, p2) { }

Ex:

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function DetailsClick(element,...product){

[Link](`${[Link]} button clicked <br>`);

var [id, name, stock, citites] = product;

[Link](`Id=${id}<br>Name=${name}<br>Stock=${stock}<br>Cities=${citites}`);

</script>

</head>

<body>

<button id="btnDetails" onclick="DetailsClick(this,1, 'TV', true, ['Delhi','Hyd'])">Details</button>

</body>

</html>

Note: Event listener can have only one argument, which is an event

argument. However it provides access to both element and event

details.
Syntax:

.addEventListener(function(event){

[Link], clientY, keyCode, charCode etc.

[Link], name, value etc.

})

“event” provides access directly to event properties.

“[Link]” provides access to element properties.

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function bodyload(){

[Link]("btnInsert").addEventListener("click",(e)=>{

[Link](`X Position=${[Link]}\nButton Value=${[Link]}`);

})
}

</script>

</head>

<body onload="bodyload()">

<button id="btnInsert" value="Insert">Insert</button>

</body>

</html>

Event Propagation / Event Bubbling

- Propagation is a mechanism where the child event simulates the parent.

- Child event propagate to parent.

- You can prevent propagation by using “stopPropagation()” method.

Syntax:

function ChildEvent(e)

[Link]();

<button onclick=“ChildEvent(event)”>

Ex:
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function NavClick(){

alert("Navbar Clicked");

function SearchClick(e){

[Link]();

alert("Search Clicked");

</script>

</head>

<body>

<nav onclick="NavClick()" style="border:1px solid black; padding: 10px;">

<h3>Navbar</h3>

<button onclick="SearchClick(event)">Search</button>

</nav>

</body>
</html>

Preventing Default Events:

- HTML generic elements have pre-defined actions.

- They have default events that fire-up along with custom events.

- You can stop default events using “preventDefault()” method.

Syntax:

function Submit(e)

[Link]();

<form onsubmit=“Submit(event)”>

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>
<script>

function FormSubmit(e){

[Link]();

alert('Form Submitted to Server');

</script>

</head>

<body>

<form onsubmit="FormSubmit(event)">

User name :

<input type="text" name="user">

<button type="submit">Submit</button>

</form>

</body>

</html>

Page-28

Events Examples

1. What is Event

2. Event Handler
3. Event Listener

4. Events Args

5. Propagation

6. Prevent Default

What is Event Loop?

- It is the process of executing tasks in specific order.

- Javascript event loop follows the order of execution

1st Priority Normal Task

2nd Priority Micro Task

3rd Priority Macro Task

- Micro task is configured using “Promise”.

- Macro task is configure using “setTimeout()”.

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>
function StartClick(){

setTimeout(()=>{

[Link]("Macro Task");

},0);

var action = new Promise((resolve, reject)=>{

resolve("Microtask");

});

[Link](response=>{

[Link](response);

})

[Link]("Normal Task");

</script>

</head>

<body>

<button onclick="StartClick()">Start</button>

</body>

</html>
What is Event Profiling?

- It is the process of tracking the performance of events in debugger.

- You can go to browser debugger and select performance to track the events.

Browser Events

- Browser window object provides various events that you can use for elements in page.

- Browser events are of various groups

1. Mouse Events

2. Keyboard Events

3. Button Events

4. Clipboard Events

5. Form Events etc.

Mouse Events:

onmouseover

onmouseout

onmousedown

onmouseup

onmousemove
Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<style>

nav img {

border:4px solid gray;

padding: 5px;

nav img:hover {

border: 4px solid blue;

cursor: grab;

</style>

<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/[Link]">

<script>

function bodyload(){

fetch("../data/[Link]")
.then(res=>[Link]())

.then(mobiles=>{

[Link](mobile=>{

var img = [Link]("img");

[Link] = [Link];

[Link]="100";

[Link]="100";

[Link]="my-2";

[Link]("mouseover",()=>{

[Link]("imgMobile").src = [Link];

})

[Link]("nav").appendChild(img);

})

})

</script>

</head>

<body class="container-fluid" onload="bodyload()">

<div class="row mt-4">

<div class="col-2">

<nav></nav>

</div>
<div class="col-10">

<img width="400" height="500" id="imgMobile">

</div>

</div>

</body>

</html>

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function Animate(e){

var flag = [Link]("img");

[Link] = "fixed";

[Link] = [Link] + "px";

[Link] = [Link] + "px";

}
</script>

</head>

<body onmousemove="Animate(event)">

<div style="height:1000px"> move mouse pointer </div>

<img src="../public/images/[Link]" width="50" height="50">

</body>

</html>

Keyboard Events

onkeyup

onkeydown

onkeypress

- Keyup and keydown are good for verifying the chars.

- Keypress is good for verifying the character code. [ASCII]

Element State Events

onfocus

onblur

onchange

Clipboard Events
oncut

oncopy

onpaste

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

</head>

<body>

<dl>

<dt>Your Account Number</dt>

<dd><input type="text" oncopy="alert('text copied')"></dd>

<dt>Verify Account Number</dt>

<dd><input type="text" onpaste="return false"></dd>

</dl>

</body>

</html>
Button Events

onclick

ondblclick

oncontextmenu [right click]

onselectstart

Note: You can disable any event with function that return false.

Syntax:

[Link] = () => false;

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

[Link] = function(){

alert("Right Click Not Allowed");

return false;
}

[Link] = function(){

return false;

</script>

</head>

<body>

<h2>Right Click Disabled on this page</h2>

</body>

</html>

Page-29

State Management and Modules

State Management

- Web applications use “http” as protocol.

- Http is a stateless protocol.

- It can’t remember information between pages.

- It uses the mechanism “Go-Get-Forget”.


GO : Connect with server

GET : Gets response from server

FORGET : Cleans up information from server

- Stateless nature is good for server as it manages memory.

- It is not good for application as it can’t remember data between requests.

- State Management is a technique of allocating memory to store data and use

across requests.

- You can manage state both

a) Client Side

b) Server Side

- Client Side state allocates memory on client device, which can be

a) Query String

b) Session Storage

c) Local Storage

d) Cookies

Query String

- It appends data to URL and stores in browser address bar.

- It is a key and value collection.


- Form submits data as query string when submitted on GET request.

- You can access query string using “[Link]”.

- Query string can be converted into key / value using URLSearchParams().

Ex:

state/[Link]

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

</head>

<body>

<form action="./[Link]">

<dl>

<dt>User Name</dt>

<dd><input type="text" name="uname"></dd>

</dl>

<button>Login</button>

</form>

</body>
</html>

State/[Link]

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function bodyload(){

var uname = new URLSearchParams([Link]).get("uname");

[Link]("lblUser").innerHTML = `Hello ! ${uname}`;

function Signout(){

[Link] = "./[Link]";

</script>

</head>

<body onload="bodyload()">
<h2>Dashboard</h2>

<div style="display: flex; justify-content: space-between;">

<span id="lblUser"></span>

<button onclick="Signout()">Signout</button>

</div>

</body>

</html>

Session Storage

- It is a browser storage.

- You can store complex data.

- It is temporary storage.

- It is deleted when browser is closed.

- It is not accessible across tabs in browser.

Syntax:

[Link](key, value)

.getItem(key)

.removeItem(key)

.clear()

Ex:
state/[Link]

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function LoginClick(){

var username = [Link]("uname").value;

[Link]("uname", username);

[Link] = "./[Link]";

</script>

</head>

<body>

<dl>

<dt>User Name</dt>

<dd><input type="text" id="uname"></dd>


</dl>

<button onclick="LoginClick()">Login</button>

</body>

</html>

state/[Link]

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function bodyload(){

var uname = [Link]("uname");

if(uname===null){

[Link] = "./[Link]";

} else {

[Link]("lblUser").innerHTML = `Hello ! ${uname}`;

}
}

function Signout(){

[Link]("uname");

[Link] = "./[Link]";

</script>

</head>

<body onload="bodyload()">

<h2>Dashboard</h2>

<div style="display: flex; justify-content: space-between;">

<span id="lblUser"></span>

<button onclick="Signout()">Signout</button>

</div>

</body>

</html>

Local Storage

- It is permanent storage of browser.

- It is accessible across tabs.

- It needs to be removed explicitly.


Syntax:

[Link](key,value)

.getItem(key)

.removeItem(key)

.clear()

Ex:

state/[Link]

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function LoginClick(){

var username = [Link]("uname").value;

[Link]("uname", username);

[Link] = "./[Link]";

</script>
</head>

<body>

<dl>

<dt>User Name</dt>

<dd><input type="text" id="uname"></dd>

</dl>

<button onclick="LoginClick()">Login</button>

</body>

</html>

state/[Link]

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>
function bodyload(){

var uname = [Link]("uname");

if(uname===null){

[Link] = "./[Link]";

} else {

[Link]("lblUser").innerHTML = `Hello ! ${uname}`;

function Signout(){

[Link]("uname");

[Link] = "./[Link]";

</script>

</head>

<body onload="bodyload()">

<h2>Dashboard</h2>

<div style="display: flex; justify-content: space-between;">

<span id="lblUser"></span>

<button onclick="Signout()">Signout</button>

</div>

</body>
</html>

Cookies

- Cookies are simple text documents.

- You can store complex data of client in a cookie.

- Cookie can be of 2 types

a) in-memory cookie [temporary]

b) persistent cookie [permanent]

- Persistent cookie requires an expiry date and time.

- It is automatically removed for memory on specified date and time.

Syntax:

[Link] = `name=value; expires=${new Date(‘yy-mm-dd’)}`;

- To remove cookie you have to set cookie empty with expiry date as

any elapsed date.

Ex:

state/[Link]

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function LoginClick(){

var username = [Link]("uname").value;

[Link] = `uname=${username};expires=${new Date('2026-01-11')}`;

[Link] = "./[Link]";

</script>

</head>

<body>

<dl>

<dt>User Name</dt>

<dd><input type="text" id="uname"></dd>

</dl>

<button onclick="LoginClick()">Login</button>

</body>
</html>

state/[Link]

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

function bodyload(){

var uname = [Link]([Link]("=")+1);

if(uname===null){

[Link] = "./[Link]";

} else {

[Link]("lblUser").innerHTML = `Hello ! ${uname}`;

function Signout(){
[Link] = `uname=''; expires=${new Date("2026-01-08")}`;

[Link] = "./[Link]";

</script>

</head>

<body onload="bodyload()">

<h2>Dashboard</h2>

<div style="display: flex; justify-content: space-between;">

<span id="lblUser"></span>

<button onclick="Signout()">Signout</button>

</div>

</body>

</html>

Javascript Module System

- Module refers to a portion of component.

- Modular refers to part-by-part.

- Libraries use legacy system which loads every component but uses only few.

It is heavy on applicaton.

- Modular approach allows to use only the required. It makes application

light weight and faster.

- Javascript has various module systems


a) Common JS

b) UMD (Universal Module Distribution)

c) AMD (Asynchronous Module Distribution)

d) ESModule

- Javascript in browser use “EsModule”, which requires the script type as

“module”.

<script type=“module”>

</script>

- Every JS file is considered as a module.

[Link] => home module

- A module can have

a) variables

b) functions

c) classes etc.

- Every member is private inside module, in order to access outside module

you have to mark them as “export”.

export const name = value;

export function name() { }


- You can export after declaring a member by using “default”.

const name = value;

export default name;

- Every module can have only one default export.

- You can import and use the module members from any page.

import default_member, { others } from “[Link]”

Ex:

[Link]

export var title = "Home Page";

export var subtitle = "Welcome to online shopping";

function Hello(){

return "Hello ! Amazon";

export function Welcome(){


return "Welcome to Amazon";

export default Hello;

[Link]

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script type="module">

import Hello, { title, subtitle, Welcome } from "./[Link]";

[Link]("h1").innerHTML = title;

[Link]("p").innerHTML = subtitle + "<br>" + Welcome() + "<br>" + Hello();

</script>

</head>

<body>

<h1></h1>

<p></p>
</body>

</html>

Page-30

Module and Class of OOP


Sudhakar Sharma (Sudhakar Sharma Naresh IT)•10 Jan
Module System

-How to Export Members

-Default Export

-Import

- If different modules have same name members then it leads to ambiguity.

- You have to import members using aliasing technique.

Syntax:

import { name as alias } from “[Link]”;

- You can import all members from a module using “*” meta character and

set alias.

Syntax:

import * as alias from “[Link]”;


[Link]

[Link]

Ex:

[Link]

export function Add(a,b){

return a + b;

export function Sub(a,b){

return a - b;

export function Mul(a,b){

return a - b;

[Link]

export function Title()

return "Admin Home";


}

[Link]

export function Title(){

return "User Home";

[Link]

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script type="module">

import { Title as AdminTitle } from "./[Link]";

import { Title as UserTitle } from "./[Link]";

import * as calc from "./[Link]";

[Link]("h1").innerHTML = AdminTitle();
[Link]("p").innerHTML= UserTitle();

[Link]("div").innerHTML = `Add=${[Link](20,30)}`;

</script>

</head>

<body>

<h1></h1>

<p></p>

<div></div>

</body>

</html>

Javascript Class - Class is a program template.

- It provides pre-defined data and logic which you customize and implement

according to requirements.

- Class enable easy reusability and extensibility.

- However class is tedious. [heavy, slow, complex..]

- If a class is designed for business requirements then it is referred as Entity.

- If class is design for data requirements then it is known as Modal.

- Class acts as a Blue Print for creating multiple instances.

Configuring Class

1. Declaration
class Name

2. Expression

const Name = class {

Class Members

1. Property

2. Accessor

3. Method

4. Constructor

Property

- It is used to store data.

- It can store any type of data.

- It is mutable.

Syntax:

class Product
{

Name = “TV”;

Price = 34000;

Stock = true;

Cities = [ ];

Rating = { };

- You can access class members by using instance of class, if they are

non-static.

- Static members are accessible by class name.

- Javascript ES6+ version support Prefixes

a) _ underscore : It marks for internal access

b) # hash : It restricts access inside class only.

Syntax:

class Product

_Name = value;

#Price = value;

}
- JavaScript ES7+ versions support static members.

- It allows a static keyword for members.

Static

- It refers to continuous memory.

- Memory allocated for first object will continue for other objects.

- Static members are accessible inside or outside class by using class name.

Non Static

- It refers to discrete memory.

- Memory is newly allocated for every object.

- Non static member is accessible inside class using “this” keyword

and outside class using instance of class.

Syntax:

class Demo

static s = 0; // continuous

n = 0; // discrete

}
Ex:

<script>

class Demo

static s = 0;

n = 0;

Print(){

Demo.s = Demo.s + 1;

this.n = this.n + 1;

[Link](`s=${Demo.s} n=${this.n}<br>`);

let obj1 = new Demo();

[Link]();

let obj2 = new Demo();

[Link]();

let obj3 = new Demo();

[Link]();

</script>
Accessors

- Accessor provides a fine grained control over property.

- You can manage read and write operations on property using accessors.

- They are 2 types

a) get() Getter

b) set() Setter

- Getter can read and return a value of property.

- Setter can assign a new value into property.

Syntax:

get aliasName()

return property;

set aliasName(newValue)

property = newValue;

Ex:
<script>

let username = prompt("Enter User Name");

let role = prompt("Enter your role", "admin | user");

let productname = prompt("Enter Product Name");

class Product

_productName;

get ProductName(){

return this._productName;

set ProductName(newName){

if(role==="admin"){

this._productName = newName;

} else {

[Link](`Hello ! ${username} you are not authorized to set product name`);

let obj = new Product();

[Link] = productname;

if([Link])

{
[Link](`Product Name = ${[Link]}`);

</script>

Method

- It defines the logic for class.

- Methods are actions performed by object.

- Method can be void or with return.

- It is same like functions in Javascript.

- Class will not allow function as class member.

Syntax:

class Name

Method(params)

return value; // or can be void

Constructor
- A constructor is used for instantiation.

- Instantiation is the process of creating object for class.

- It is a special type of subroutine that executes automatically for every object.

- In JS constructor is anonymous with constructor keyword.

Syntax:

class Name

constructor(){ }

Ex:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Document</title>

<script>

class Database

constructor(dbName){
[Link](`Connected with ${dbName} database<br>`);

Insert(){

[Link](`Record Inserted..`);

Update(){

[Link](`Record Updated..`);

Delete(){

[Link](`Record Deleted..`);

function Action(command){

switch(command){

case "Insert":

let ins = new Database([Link]("select").value);

[Link]();

break;

case "Update":

let update = new Database([Link]("select").value);

[Link]();
break;

case "Delete":

let del = new Database([Link]("select").value);

[Link]();

break;

</script>

</head>

<body>

<select>

<option>Select Database</option>

<option>Oracle</option>

<option>MySQL</option>

<option>MongoDB</option>

</select>

<button onclick="Action('Delete')">Delete</button>

<button onclick="Action('Insert')">Insert</button>

<button onclick="Action('Update')">Update</button>

</body>

</html>
THIS IS THE END

You might also like