JAVASCRIPT

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 52

JavaScript

- JavaScript is a light weight interpreted and JIT compiled programming language.


- It is light weight as it occupies less memory.
- Interpreted allows to translate line-by-line of program.
- Compiled allows to translate all lines in a program simultaneously at the same
time.
- Compiling is again classified into 2 types
a) JIT
b) AOT
- JIT is "Just-in-Time", which loads the program into browser and compiles in
browser.
- AOT is "Ahead-of-Time, which compiles the program before it loads into browser.
- To implement AOT you need various JavaScript compilers
a) V8
b) Babel
- JavaScript is a language that supports various programming approaches [Paradigm]
a) Structural
b) Imperative
c) Functional
d) Object Oriented etc..

Note: JavaScript is not an OOP language. It supports few features of OOP.

- JavaScript is a language used in various application areas


a) Client Side
b) Server Side
c) Database
d) Animation tools

JavaScript Client Side:


- JavaScript is used client side to handle various functionalities like
a) DOM Manipulations
b) BOM Interactions
c) Validations etc..
- The aim of client side script is to reduce burden on server.
- DOM manipulation includes [Document Object Model]
a) Adding elements into page
b) Removing elements from page
c) Updating data into elements
d) Repeating elements
e) Data Binding, Class Binding, Style Binding, Event Binding etc..
- BOM manipulation includes [Browser Object Model]
a) Browser location
b) Navigator
c) History
d) Window
e) Document
- Validation is the process of verifying user input to ensure that contradictory
and unauthorized data is not get stored into database.
- JavaScript provides various methods to validate user input.

Evolution of JavaScript:

- CERN labs [Council for European Research and Nuclear] started ECMA Script as a
scripting language for browsers in early evolution of internet.
- The first browser is "Mosaic", which uses ECMA Script.
- Tim Berners Lee introduced "Web" in early 1990's.
- Netscape Communicator is the popular browser for Web in early days of web.
- Netscape appointed "Brendan Eich" to develop a script for their browser.
- Brendan Eich designed a script and named it as "Mocha", later renamed as "Live
Script".
- Netscape given the responsibility of Live Script to "Sun Microsystems".
- Sun Microsystems and Netscape together named "JavaScript".
- In year 2000 Netscape stopped its services and given the responsibility of
JavaScript to "ECMA".
- JavaScript is now developed and maintained by ECMA.
- The popular ECMA Versions of JavaScript are
ECMA 2015 ES5
ECMA 2016 ES6
ECMA 2017 ES7

ECMA 2022 ESNext

2...
Issues with JavaScript:

- It is not a strongly typed language.


* It is implicitly typed.
* It doesn't have any restriction for type of data you store.

var age = 22; // number


age = "John"; // string - it is valid to assign a string

- It is not implicitly strictly typed.


* Strictly typed allows to restrict the code according to coding rules.
* JavaScript is not implicitly strictly typed.
* This leads to lot of code inconsistency.
* You have to turn the strict mode ON explicitly.

"use strict";

- It is not an OOP language.


* Limited extensibility
* No code level security
* Limited reusability

- JavaScript can be disabled in browser.

FAQ: What is solution?


Ans: TypeScript. It is just an alternative for JavaScript.
TypeScript trans compiles into JavaScript.
TypeScript designed and maintained by "Microsoft".

JavaScript with HTML


[JS in Web Page]

- JavaScript functions can be


a) Inline
b) Embedded
c) In External File

Inline:
- You can define JS functions directly for element in UI design.
- It is faster in execution but can't be reused across elements and requests.

Syntax:
<button onclick="window.print()"> Print </button>

Embedded:
- JavaScript functions are embedded into page by using <script> container.
- You can embed script into <head> or <body> section.
- The MIME type for script is "text/javascript" or "language=javascript".

Syntax:
<script type="text/javascript"> <script language="javascript">
</script> </script>

- If JavaScript is used with Module systems then type="module".

Syntax:
<script type="module">
</script>

- You can turn ON strict mode for the functions you embed in page.

Syntax:
<script type="text/javascript">

"use strict";

// your functions

</script>

- You can target the script for legacy browsers by enclosing the functions within
HTML comments.

Syntax:
<script type="text/javascript">

"use strict";

<!--

function name(){

-->

</script>

Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inline</title>
<script type="text/javascript">
"use strict";
<!--
function PrintPage(){
window.print();
}
-->
</script>
</head>
<body>
<!-- user can print the page by clicking print button -->
<h2>Your Ticket</h2>
<button onclick="PrintPage()">Print</button>
</body>
</html>

FAQ: How to verify JavaScript status in browser? [enabled or not]


Ans: By using HTML <noscript> element.

Syntax:
<body>
<noscript>
Please enable JS on your browser.
</noscript>
</body>

Script in External File:


- You can write JS functions in a separate script file with extension ".js"
- You can link the script file to any page and access functions across pages.
- However using an external file will increase the number of requests and also page
load time.

Ex:
1. Add a new script file into scripts folder

"ticket.js"

"use strict";
function PrintPage() {
window.print();
}

2. Link script file to any HTML page

<head>
<script type="text/javascript" src="../src/scripts/ticket.js"> </script>
</head>

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

Note: You can minify the script file for production.

JavaScript Reference Techniques

- HTML present static DOM.


- CSS uses "CSSOM" to make the DOM responsive and interactive.
- JavaScript converts the static DOM into dynamic DOM.
- JS can take control over HTML DOM elements by using various techniques
1. Refer by using DOM hierarchy
- DOM have a hierarchy of elements.
- "window" is the parent.
- "document" refers to page in window.
- Inside document elements arranged in hierarchical order.
- JS can access in the same order, which is the native technique.
- It is faster is accessing with DOM hierarchy.

Syntax:
window.document.images[]
window.document.forms[]
window.document.forms[].elements[]

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">
function bodyload(){
window.document.images[0].src = "../public/images/women-fashion.jpg";
window.document.forms[0].elements[1].value = "Register";
window.document.forms[1].elements[1].value = "Login";
}
</script>
</head>
<body onload="bodyload()">
<div>
<img width="100" height="100">
</div>
<div>
<form>
<h2>Register</h2>
Your Email : <input type="email"> <input type="button">
</form>
</div>
<div>
<form>
<h2>Login</h2>
Your OTP : <input type="text"> <input type="button">
</form>
</div>
</body>
</html>

3....

JavaScript refers HTML elements


1. DOM Hierarchy

2. JavaScript can refer elements by using "name"


- Every HTML element can have a reference name, which is defined by using "name"
attribute.
- JavaScript can access element by using name.
Syntax:
<img name="poster">

poster.src="./images/pic.jpg";

- You can't refer a child element directly without referring to its generic parent.
- "Name" attribute can be common of several elements, which conflicts with
reference.

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">
function bodyload(){
poster.src="../public/images/men-fashion.jpg";
frmRegister.btnRegister.value = "Register";
frmLogin.btnLogin.value = "Login";

}
</script>
</head>
<body onload="bodyload()">

<div>
<img width="100" height="100" name="poster">
</div>
<div>
<form name="frmRegister">
<h2>Register</h2>
Your Email : <input type="email" name="txtEmail"> <input
name="btnRegister" type="button">
</form>
</div>
<div>
<form name="frmLogin">
<h2>Login</h2>
Your OTP : <input type="text" name="txtOtp"> <input name="btnLogin"
type="button">
</form>
</div>
</body>
</html>

3. JavaScript can refer and access elements by using "ID"


- Every element can have a unique ID reference.
- JavaScript provides a "document" method "getElementById()", which can access
element with "ID" reference.
- You can access any child element directly without referring to its generic
parent.

Syntax:
<img id="poster">

document.getElementById("poster").src="some_path";
- ID is a selector for CSS, where it can be common for several elements.
- This leads to conflicts with elements and their ID in page. As HTML element can't
have multiple ID references.

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">
function bodyload(){
document.getElementById("poster").src = "../public/images/kids-
fashion.jpg";
document.getElementById("btnRegister").value = "Register";
document.getElementById("btnLogin").value = "Login";
}
</script>
</head>
<body onload="bodyload()">

<div>
<img width="100" height="100" id="poster" name="poster">
</div>
<div>
<form name="frmRegister">
<h2>Register</h2>
Your Email : <input type="email" name="txtEmail"> <input
id="btnRegister" type="button">
</form>
</div>
<div>
<form name="frmLogin">
<h2>Login</h2>
Your OTP : <input type="text" name="txtOtp"> <input id="btnLogin"
type="button">
</form>
</div>
</body>
</html>

4. JavaScript can refer HTML elements by using CSS selectors

- CSS provides various selectors to select HTML elements in page.


- JavaScript can use the same selectors to select and define dynamic functionality.
- It uses "document" method called "querySelector()".

Syntax:
<img id="poster">
<input type="button" class="btn-primary">
<p>

document.querySelector("#poster")
document.querySelector(".btn-primary")
document.querySelector("p")

- Same selector is used for multiple elements, which again leads to conflicts in
reference.
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">
function bodyload(){
document.querySelector("img").src = "../public/images/women-
fashion.jpg";
document.querySelector("#btnRegister").value = "Register";
document.querySelector(".btn-primary").value = "Login";
}
</script>
</head>
<body onload="bodyload()">

<div>
<img width="100" height="100" id="poster" name="poster">
</div>
<div>
<form name="frmRegister">
<h2>Register</h2>
Your Email : <input type="email" name="txtEmail"> <input
id="btnRegister" type="button">
</form>
</div>
<div>
<form name="frmLogin">
<h2>Login</h2>
Your OTP : <input type="text" name="txtOtp"> <input class="btn-primary"
type="button">
</form>
</div>
</body>
</html>

JavaScript Output Techniques

- Output is the process of rendering result to user.


- You can display any value or result of any expression in the UI.
- The various JavaScript output techniques include

1. alert()
2. confirm()
3. document.write()
4. innerText
5. innerHTML
6. outerHTML
7. textcontent()
8. console methods
etc..

alert():
- It pops up a message box in browser window.
- It can display the result of any expression or directly a value.
- It is RC type, hence you can display only plain content.
- You can use "\n" for line break in message.

Syntax:
alert("value / expression");
alert("Hello !");
alert(30);
alert(20 + 20);
alert("Record Number : " + (10+1) + " Deleted");
alert("line-1\nline-2");

Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Output</title>
<script type="text/javascript">
function DeleteClick(){
alert("Delete Record\nRecord Deleted Successfully..");
}
</script>
</head>
<body>
<p>Click Delete button to remove record</p>
<button onclick="DeleteClick()">Delete</button>
</body>
</html>

confirm():
- It is similar to alert but allows to cancel.
- It is a Boolean method that returns true or false.
- It returns true on OK and 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>Output</title>
<script type="text/javascript">
function DeleteClick(){
flag = confirm("Delete Record\nAre you sure?");
if(flag==true)
{
alert("Record Deleted");
}
else
{
alert("Canceled..");
}
}
</script>
</head>
<body>
<p>Click Delete button to remove record</p>
<button onclick="DeleteClick()">Delete</button>
</body>
</html>

document.write():
- It renders output on new screen of same page.
- It renders inside browser workspace as a part of page.
- It supports complex markup to render.
- It can render message, expression and markup.

Syntax:
document.write("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>Output</title>
<script type="text/javascript">
function DeleteClick(){
flag = confirm("Delete Record\nAre you sure?");
if(flag==true)
{
document.write("<h3 style='color:red'>Record Deleted
Successfully..</h3><a href='output.html'>Back</a>")
}
else
{
alert("Canceled..");
}
}
</script>
</head>
<body>
<p>Click Delete button to remove record</p>
<button onclick="DeleteClick()">Delete</button>
</body>
</html>

innerText & textContent


- These allows to render output into any HTML container element that can display
text content.
- They will not allow rich text formats.
- They can display only plain text.

Syntax:
<p> </p>

document.querySelector("p").textContent = "Some text";


document.querySelector("p").innerText = "Some text";

innerHTML:
- It is similar to innerText and textContent but allows all rich formats with
markup.

Syntax:
document.querySelector("p").innerHTML = "Some text | <markup> </markup>";

- It renders the new markup into existing element.

outerHTML:
- It is similar to innerHTML but can replace the existing element with new element.

Syntax:

document.querySelector("p").outerHTML = "<markup> </markup>";

Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Output</title>
<script type="text/javascript">
function DeleteClick(){
flag = confirm("Delete Record\nAre you sure?");
if(flag==true)
{
document.querySelector("p").innerHTML = "<b><i
style='color:red'>Record Deleted</i></b>";
}
else
{
alert("Canceled..");
}
}
</script>
</head>
<body>
<p>Click Delete button to remove record</p>
<button onclick="DeleteClick()">Delete</button>
</body>
</html>

4.....

JavaScript Output Techniques


- alert()
- confirm()
- document.write()
- textContent
- innerText
- innerHTML
- outerHTML

Console Methods:
- Console is a command line tool of Web Browser.
- You can find console in browser developer tools.
- JavaScript allows developer to test all commands from console.
- JS logs all warning and errors in the console.
- Console methods are contextual

console.warn()
console.error()
console.debug()
console.info()
console.log()
etc..

Syntax:
console.warn("message | expression"); // RC type

Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Output</title>
<script type="text/javascript">
function DeleteClick(){
console.warn("User Clicked Delete - Initiated Delete function");
flag = confirm("Delete Record\nAre you sure?");
if(flag==true)
{
document.querySelector("p").outerHTML = "<h2>Record Deleted</h2>";
console.error("User Clicked OK - Delete Completed");
}
else
{
alert("Canceled..");
console.log("User Clicked Cancel Button");
}
}
</script>
</head>
<body>
<p>Click Delete button to remove record</p>
<button onclick="DeleteClick()">Delete</button>
</body>
</html>

Note: Console methods are only for development and testing environments, not for
production.

JavaScript Input
- Input is the process of accepting a value dynamically from user at the runtime of
application.

- JavaScript provides various input techniques, which includes

a) Query String
b) Prompt
c) Form Input Elements

Query String:
- Query String allows user to search in a document by providing values input
directly from browser address bar.
- It is appended into URL with "?"
- It comprises multiple keys and values.

Syntax:
page.html ?key1=value1&key2=value2&key3=value3 �

- JavaScript provides "location.search" to access and use query string in page.


- However you need various string handling methods to extract only the value that
you need from a string.

a) slice() : extracts chars between specified index number


b) indexOf() : returns the index number of a char in string

Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Input</title>
<script>
function bodyload(){
str = location.search;
equalPosition = str.indexOf("=");

document.getElementById("lblUser").innerHTML =
str.slice(equalPosition+1);
}
</script>
</head>
<body onload="bodyload()">
<h2>Home</h2>
<p>Hello ! <span id="lblUser"></span></p>
</body>
</html>

Prompt:
- It is an input box provided by browser window.
- It pops up an input box that allows user to input a value.

Syntax:
prompt("Message", "Default_Value");
prompt("Message");
prompt("Expression | Message");

- prompt() returns the following

a) ' ' empty string when value is not provided.


b) 'value' string provided as value
c) null when user cancel the prompt

Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Input</title>
<script>
function bodyload(){
username = prompt("Enter Name");
if(username=='') {
alert("Name can't be empty");
}
else if(username==null) {
alert("You canceled..");
}
else {
document.getElementById("lblUser").innerHTML = username;
}

}
</script>
</head>
<body onload="bodyload()">
<h2>Home</h2>
<p>Hello ! <span id="lblUser"></span></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>Input</title>
<script>
function AddClick(){
folderName = prompt("Enter Folder Name", "New_Folder");
if(folderName=='') {
alert("Folder name is required");
}
else if(folderName==null) {
alert("You canceled");
} else {
document.querySelector("p").innerHTML += "Folder Created : " +
folderName + "<br>";
}

}
</script>
</head>
<body>
<button onclick="AddClick()">Add New Folder</button>
<p></p>
</body>
</html>

Form Input Elements:


- HTML provides various form elements like textbox, checkbox, radio, listbox,
textarea, range, number, date, email etc..
- JavaScript can accept input from various form elements and use in page.

Syntax:
<input type="number" id="age">
<select id="city"> </select>
document.getElementById("age").value
document.getElementById("city").value

Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Input</title>
<script>
function AddClick(){
folderName = document.getElementById("txtName").value;

if(folderName=='')
{
document.getElementById("error").innerHTML = "Name Required";
}else {
document.querySelector("p").innerHTML += "Folder Created : " +
folderName + "<br>";
document.getElementById("txtName").value = "";
document.getElementById("error").innerHTML = "";
}

}
</script>
</head>
<body>
<input type="text" id="txtName" placeholder="New folder name">
<button onclick="AddClick()">Add New Folder</button>
<div id="error" style="color:red"></div>
<p></p>
</body>
</html>

5.....

Input Techniques
- Query String
- Prompt
- Form Elements

Ex:
1. inox.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inox</title>
<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/bootstrap-
icons.css">
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<script src="../node_modules/bootstrap/dist/js/bootstrap.bundle.js"></script>
<script src="../src/scripts/inox.js"></script>
</head>
<body class="container-fluid">
<button id="btnBooking" class="btn btn-primary mt-2" data-bs-target="#booking"
data-bs-toggle="modal">Quick Booking</button>
<div class="modal fade" id="booking">
<div class="modal-dialog modal-fullscreen">
<div class="modal-content">
<div class="modal-header">
<h2 id="lblTitle">Quick Booking</h2>
<button class="btn btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<div class="d-flex justify-content-between">
<div>
<select class="form-select" id="lstMovies">
<option>Select Movie</option>
<option>DEADPOOL AND WOLVERINE</option>
<option>ULAJH</option>
</select>
</div>
<div>
<select class="form-select" id="lstDate">
<option>Select Date</option>
<option>Today, 2 Aug</option>
<option>Tomorrow, 3 Aug</option>
</select>
</div>
<div>
<select class="form-select" id="lstCinema">
<option>Select Cinema</option>
<option>INOX B'Hills</option>
<option>PVR KPHB</option>
</select>
</div>
<div>
<select class="form-select" id="lstTiming">
<option>Select Timing</option>
<option>08:30 PM</option>
<option>10:30 PM</option>
</select>
</div>
<div>
<button id="btnBook" data-bs-dismiss="modal" class="btn
btn-primary" onclick="BookClick()">Book</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="summaryContainer" style="display: none;">
<dl class="w-25 row">
<h3>Booking Summary</h3>
<img id="imgPoster" width="100%" height="300">
<dt class="col-3 my-2">Movie</dt>
<dd class="col-9 my-2" id="lblName"></dd>
<dt class="col-3 my-2">Date</dt>
<dd class="col-9 my-2" id="lblDate"></dd>
<dt class="col-3 my-2">Cinema</dt>
<dd class="col-9 my-2" id="lblCinema"></dd>
<dt class="col-3 my-2">Timing</dt>
<dd class="col-9 my-2" id="lblTiming"></dd>
<dd class="col">
<button data-bs-target="#booking" data-bs-toggle="modal" class="btn
w-100 btn-warning bi bi-pen-fill" onclick="ModifyClick()"> Modify Booking </button>
</dd>
</dl>

</div>
</body>
</html>

2. src/scripts/inox.js

function BookClick(){
document.getElementById("btnBooking").style.display = "none";
document.getElementById("summaryContainer").style.display = "block";

movieName = document.getElementById("lstMovies").value;

document.getElementById("lblName").innerText = movieName;
document.getElementById("lblDate").innerText =
document.getElementById("lstDate").value;
document.getElementById("lblCinema").innerText =
document.getElementById("lstCinema").value;
document.getElementById("lblTiming").innerText =
document.getElementById("lstTiming").value;

if(movieName=="DEADPOOL AND WOLVERINE"){


document.getElementById("imgPoster").src =
"../public/images/deadpool.jpg";
} else {
document.getElementById("imgPoster").src = "../public/images/ulajh.jpg";
}

function ModifyClick(){
document.getElementById("lblTitle").innerText = "Modify Booking";
document.getElementById("btnBook").innerText = "Save";
document.getElementById("btnBook").className = "btn btn-success";
}

Ex:
product.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Product</title>
<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/bootstrap-
icons.css">
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<script src="../node_modules/bootstrap/dist/js/bootstrap.bundle.js"></script>
<script type="text/javascript">
function RegisterClick(){
document.getElementById("lblName").innerText =
document.getElementById("txtName").value;
document.getElementById("lblPrice").innerText =
document.getElementById("txtPrice").value;
document.getElementById("lblCity").innerText =
document.getElementById("lstCities").value;

stock = "";
stockCheckbox = document.getElementById("optStock");

if(stockCheckbox.checked) {
stock = "Available";
} else {
stock = "Out of Stock";
}

document.getElementById("lblStock").innerText = stock;

}
</script>
</head>
<body class="container-fluid">
<div id="registerContainer" class="w-25">
<h2>Register Product</h2>
<dl>
<dt>Name</dt>
<dd><input type="text" id="txtName" class="form-control"></dd>
<dt>Price</dt>
<dd><input type="number" id="txtPrice" class="form-control"></dd>
<dt>Shipped To</dt>
<dd>
<select id="lstCities" class="form-select">
<option>Select City</option>
<option>Delhi</option>
<option>Hyd</option>
</select>
</dd>
<dt>Stock</dt>
<dd class="form-switch">
<input type="checkbox" id="optStock" class="form-check-input">
<label class="form-check-label">Available</label>
</dd>
</dl>
<button class="btn btn-primary w-100" data-bs-target="#details" data-bs-
toggle="modal" onclick="RegisterClick()">Register</button>
<div class="modal fade" id="details">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h2>Product Details</h2>
</div>
<div class="modal-body">
<dl>
<dt>Name</dt>
<dd id="lblName"></dd>
<dt>Price</dt>
<dd id="lblPrice"></dd>
<dt>City</dt>
<dd id="lblCity"></dd>
<dt>Stock</dt>
<dd id="lblStock"></dd>
</dl>
</div>
<div class="modal-footer">
<button class="btn btn-primary" data-bs-
dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

JavaScript Language
1. Variables
2. Data Types
3. Operators
4. Statements
5. Functions
6. OOP Features

6.....

JavaScript Language

Variables in JavaScript:

- Variables are storage locations in memory, where you can store a value and use it
as a part of any expression.

- Variable configuration comprises 3 phases

a) Declaration
b) Assignment
c) Initialization

- If JavaScript is not in strict mode the declaring variable is optional, but it is


not recommended.

- Variables in JavaScript are declared by using following keywords

a) var
b) let
c) const

- Declaring defines the keyword with variable name

var x ;

- Assignment is the process of storing a value into variable reference after


declaring a variable.

x = 10;
- Initialization is the process of assigning a value into variable at the time of
declaration.

var y = 20;

Syntax:
var x; // Declaring
x = 10; // Assignment
x = 20; // Assignment

var y=30; // Initialization


y=40; // Assignment

FAQ: What is difference between var, let & const ?

var
- It configures a function scope variable.
- You can declare in any block of a function and access from any another block.
- It supports declaring, assignment and initialization.
- It supports shadowing.
- Shadowing is the process of re-declaring or re-initializing a variable with same
name identifier with in the scope.

{
var x = 10; // initialization
x = 20; // assignment
var x = 30; // shadowing
}
Ex:
<script>
function f1()
{
var x; // declaring
x = 10; // assignment
if(x==10)
{
var y = 20; // initialization
y = 30;
var y; // shadowing
y=50;
}
document.write("x=" + x + "<br>y=" + y);
}
f1();
</script>

- It supports hoisting.
- Hoisting is a mechanism that allows to use variable and have a declaration or
initialization later. [after using you can declare]
- "var" can hoist your variable so that there is no ordered dependency in declaring
and using.

Ex:
<script>
"use strict";
function f1()
{
x = 20;
document.write("x=" + x);
var x; // hoisting
}
f1();
</script>

let :
- It defines a block scope variable.
- Block scope variable works in closure.
- It is accessible in the specified block and its inner block.
- It supports declaring, assignment and initialization.
- It will not support shadowing and hoisting.

Ex:
<script>
"use strict";
function f1()
{
let x;
x = 10;
if(x==10)
{
let y = 20;
y = 30;
document.write("x=" + x + "<br>y=" + y);
}

}
f1();
</script>

const:
- It defines a block scope variable.
- It will not allow declaring and assignment.
- It supports only initialization.
- It will not support shadowing and hoisting.

Syntax:
const x = 10;
x = 20; // invalid

7....

JavaScript Variables
- Configuration
- Declaring
- Assigning
- Initialization
- var, let, const
- Shadowing
- Hoisting

Global Scope:
- Global allows to access variable from any function.
- It is defined at module level.
- You can define a global variable using var, let or const.
Syntax:
var x = 10;
let y = 20;
const z = 30;

f1() {
// can access x, y, z
}
f2() {
// can access x, y, z
}

- You can define a variable inside function using "window" object and make it
global in access.

FAQ: Can we define a global variable in side function?


Ans: Yes, if you are using JavaScript BOM. [Browser Object Model]

Syntax:
window.variableName = value;

Ex:
<script>
"use strict";
var x = 10;
let y = 20;
const z = 30;
function f1(){
window.a= 100;
document.write("F1 X=" + x + " Y=" + y + " Z=" + z + " A=" + a + "<br>");
}
function f2(){
document.write("F2 X=" + x + " Y=" + y + " Z=" + z + " A=" + a + "<br>");
}
f1();
f2();
</script>

Variable Naming:
- It must start with alphabet or underscore.
- Special chars are not recommended.
- It can't start with numeric but can be alpha numeric.

var list2;
var 2ndList; // invalid
var _2ndList; // valid - Not Good

- It can't be a keyword.

var class; // invalid


var Class; // valid
var forEach; // invalid

- It can be max 255 chars long. [ECMA Standards]


- It must speak what it is.

var products;
var product;
var employeeId;
FAQ's:
1. Can we define multiple variables with one keyword?
A. Yes.

var x, y, z;
var x=10, y=20, z=30;

var x; y, z; // y & z not defined


var x; let y, z; // valid

2. What is the value of a variable if value is not defined?


A. "undefined"

var x;
document.write("x=" + x); // x = undefined

3. How to assign same value into a series of variables?


A. In strict mode all variables must be declared, then you can configure value in
series types of assignment.

Syntax:
"strict mode";
var x = y = z = 10; // invalid

"strict mode";
var y, z;
var x = y = z = 10; // valid x=10, y=10, z=10

4. What is de-structuring of variables?


A. ES5+ versions support de-structuring, which allows to configure variables in a
sequential order by using "[ ]" meta character.
It uses an iterator sequence to assign values or initialize values.

Syntax:
var [x, y, z] = [10, 20, 30]; // x=10, y=20, z=30
var [x, y, z] = [10]; // x =10, y=undefined, z=undefined

Ex:
<script>

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

document.write("x=" + x + "<br>y=" + y + "<br>z=" + z);


</script>

- De-Structuring requires memory initialization.

Syntax:
var [x, y, z]; // invalid

var [x, y, z] = [ ]; // valid

- Value initialization is not required, you can assign individually.

Syntax:
var [x,y,z] = [ ];
x = 10;
y = 20; => valid
z = 30;

JavaScript Data Types

- Data Type refers to data structure.


- It defines the type, range and behaviour of data in memory.
- JavaScript is not a strongly typed language.
- However it can manage various types of data, which are classified into 2 groups

a) Primitive Data Types


b) Non-Primitive Data Types

Primitive Types:
- They are immutable types.
- They have a fixed range and structure.
- Data structure can't change dynamically.
- They are stored in memory stack.
- Stack uses LIFO [Last-in-First-out].
- JavaScript Primitive types are [ES6]

a) Number
b) String
c) Boolean
d) Null
e) Undefined
f) BIGINT
g) Symbol

8....

Number Type
- A number is JavaScript can be any one of the following. [E6+]

Signed Integer - 32
Unsigned Integer 32
Floating Point 4.5
Double 453.34
Decimal 3450.45 [29]
Exponent 2e3 2 x 10^3 = 2000
Binary 0b1010 10
Hexadecimal 0x7220
Octa 0o742
BIGINT 988481134n

- To present numbers in JavaScript you can use various converting methods.

a) toFixed(fractions)

Syntax:
var price = 45000.00;

document.write("Price=" + price); // 45000


document.write("Price=" + price.toFixed(2); // 45000.00
b) toLocaleString('region', {attributes})

Syntax:
document.write("Price=" + price.toLocaleString("en-in", { style:"currency",
currency:"INR"})

Ex:
<script>
var price = 450000.45 + 5000;

document.write("Price=" + price.toLocaleString('en-in', {style:"currency",


currency:"INR"}));
</script>

- Converting a numeric string into number requires the methods

a) parseInt()
b) parseFloat()

Syntax:
var age = "22";
parseInt(age);

var interestRate = "14.56";


parseInt(interestRate); // 14
parseFloat(interestRate); // 14.56

Ex:
<script>
var age = parseInt(prompt("Enter Your Age"));

document.write("Your current age is " + age + "<br> Next year you will be " +
(age+1));
</script>

Ex:
<script>
var rate = parseFloat(prompt("Enter Your Age"));

document.write("Your current interest rate is " + rate + "<br> Next year it


will be " + (rate+1));
</script>

Note: A numeric string in JavaScript refers to value starting with a number and can
have string chars, which are ignored while parsing.

var x = "20AB";
var y = 30;
var z = parseInt(x) + y; // 50

var x = "AB20"; // NaN


var x = "20AB30"; // 20

- You can verify number type by using the method "isNaN()".


- It is a Boolean method that returns "true" if input value is not a number.

Syntax:
var age = "33A";
if(isNaN(age))
{
document.write("Not a Number");
} else {
document.write("Verified..");
}

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">
function SubmitClick(){
var age = document.getElementById("txtAge").value;
if(isNaN(age)){
document.getElementById("lblAge").innerHTML = "Age must be a
number";
} else {
document.write("Age verified..");
}
}
</script>
</head>
<body>
<dl>
<dt>Your Age</dt>
<dd><input type="text" id="txtAge"></dd>
<dd id="lblAge" style="color:red"></dd>
</dl>
<button onclick="SubmitClick()">Submit</button>
</body>
</html>

- JavaScript provides Math object to manipulate the numbers with various


mathematical operations.
- JavaScript also provides mathematical operators to handle math operations.

Operators:
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus Division
** Power
++ Increment
-- Decrement

Math Object:
Math.PI
Math.sqrt()
Math.round()
Math.pow()
Math.floor()
Math.ceil()
Math.sin()
Math.cos()
Math.tan()
etc..

9....

<!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/bootstrap.css">
<style>
input[type="range"] {
width: 100%;
}
</style>
<script type="text/javascript">
function AmountChange(){
document.getElementById("txtAmount").value=
document.getElementById("rangeAmount").value;
}
function YearChange(){
document.getElementById("txtYears").value =
document.getElementById("rangeYears").value;
}
function RateChange(){
document.getElementById("txtRate").value =
document.getElementById("rangeRate").value;
}
function CalculateClick(){
var P = parseInt(document.getElementById("txtAmount").value);
var R = parseFloat(document.getElementById("txtRate").value)/12/100;
var N = parseInt(document.getElementById("txtYears").value) * 12;

var EMI = P * R * (Math.pow(1+R,N)) / (Math.pow(1+R,N)-1);

document.getElementById("lblResult").innerHTML = "Your monthly


installment is <b>" + EMI.toLocaleString('en-in',{style:"currency",
currency:"INR"}) + " </b>for next " + N + " months";

}
</script>
</head>
<body class="container-fluid bg-secondary">
<div class="bg-light text-dark p-4 m-4">
<div class="h4 text-center mb-4">Personal Loan EMI Calculator</div>
<div class="row my-2">
<div class="col">
Amount you need &#8377; <input type="text" id="txtAmount">
</div>
<div class="col">
for <input type="number" size="2" min="1" max="5" value="1"
id="txtYears"> years
</div>
<div class="col">
Interest rate <input type="number" id="txtRate" min="10.45"
max="18.45" value="10.45" step="0.01"> %
</div>
</div>
<div class="row my-4">
<div class="col">
<input onchange="AmountChange()" type="range" min="100000"
max="500000" value="100000" id="rangeAmount">
<div class="d-flex justify-content-between">
<span>&#8377; 1,00,000</span>
<span>&#8377; 5,00,000</span>
</div>
</div>
<div class="col">
<input onchange="YearChange()" type="range" min="1" max="5"
value="1" id="rangeYears">
<div class="d-flex justify-content-between">
<span>1</span>
<span>5</span>
</div>
</div>
<div class="col">
<input onchange="RateChange()" type="range" min="10.45" max="18.45"
value="10.45" step="0.01" id="rangeRate">
<div class="d-flex justify-content-between">
<span>10.45%</span>
<span>18.45%</span>
</div>
</div>
</div>
<div class="row my-4">
<div class="col text-end">
<button onclick="CalculateClick()" class="btn btn-
primary">Calculate</button>
</div>
</div>
<div class="my-4 text-center">
<div id="lblResult" class="fs-4"></div>
</div>
</div>
</body>
</html>

Task: Design BMI Calculator

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/bootstrap-
icons.css">
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<script>
function bodyload(){
var value = prompt("Enter BMI");
document.getElementById("lblStatus").style.marginLeft = value + "%";
}
</script>
</head>
<body class="container-fluid" onload="bodyload()">
<div class="progress mt-4">
<div class="progress-bar bg-dark" style="width: 25%;">
Under Weight below 50Kg
</div>
<div class="progress-bar bg-info" style="width: 25%;">
Normal Weight 50-68Kg
</div>
<div class="progress-bar bg-dark" style="width: 25%;">
Over Weight 68-81Kg
</div>
<div class="progress-bar bg-info" style="width: 25%;">
Obese > 81Kg
</div>
</div>
<div>
<span id="lblStatus" class="bi bi-triangle-fill">You</span>
</div>
</body>
</html>

String Type

- String is a literal with group of chars, which include alpha numeric and special
characters.
- A string literal is enclosed in
a) Double Quote " "
b) Single Quote ' '
c) Back Tick ` `

- Single and double quote are used to switch between inner and outer string.

Ex:
<script>
var link = '<a href="emi.html">EMI Calculator</a>';
document.write(link);
</script>

Ex:
<script>
var link = "<a href='emi.html'>EMI Calculator</a>";
document.write(link);
</script>

- Single and double quote string require lot of concatenation with "+" operator for
dynamic values and expressions.

- ES5+ versions support backtick which allows embedded expression by using data
binding expression "${ }"

- Binding expression in a string is allowed only for "backtick".

Syntax:
`string ${value} string ${expression} string`;

Ex:
<script>
var uname = prompt("Enter User Name");
var age = parseInt(prompt("Enter Age"));

var msg1 = "Hello !" + " " + uname + " " + "your age is" + " " + age + " " +
"you will be" + " " + (age+1) + " " + "next year<br>";
var msg2 = `Hello ! ${uname} your age is ${age} you will be ${age+1} next
year.`;
document.write(msg1);
document.write(msg2);
</script>

Ex:
<script>
var title = prompt("Enter Title");
var type = prompt("Enter Element Type");
var button = prompt("Enter Button Text");
var component = `
<div>
<label> ${title} </label>
<input type=${type}>
<button>${button}</button>
</div>
`;
document.write(component);
</script>

String Formatting and Manipulations

10 ...

1. Double Quote
2. Single Quote
3. Back Tick
4. Binding Expression ${ }

Escape Sequence:
- Several special characters in a string can escaping printing.
- To print non-printable characters you need "\" as escape sequence character.

Syntax:
var path = "D:\Project";
document.write(path); // D:Project

var path = "D:\\Project"; // D:\Project

String Formatting Methods:


- JavaScript provides various methods to format a string dynamically.
- Formatting includes font, style, color, size, effects etc.

fontsize()
fontcolor()
bold()
italics()
underline()
sup()
sub()
strike()
toUpperCase()
toLowerCase()
etc.

Syntax:
var msg = "Welcome";
msg.bold().italics().fontcolor('red').fontsize(6);

Ex:
<script>
var msg = "Welcome to JavaScript";
document.write(msg.bold().fontcolor('#f0f').fontsize(7));
</script>

Note: Formatting methods like styles, effects and color will not apply for RC type
elements.

document.querySelector("p).innerText = "Welcome".bold();

<b> Welcome </b>

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 ChangeCase(){
var code = document.getElementById("txtCode").value;
document.getElementById("txtCode").value = code.toUpperCase();
}
</script>
</head>
<body>
<dl>
<dt>Bank IFSC Code</dt>
<dd>
<input type="text" id="txtCode" onblur="ChangeCase()">
</dd>
</dl>
</body>
</html>

Ex: String Formatting

<!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>
dd, dt {
margin-bottom: 10px;
}
</style>
<script>
function ApplyClick(){
var size = document.getElementById("txtFontSize").value;
var color = document.getElementById("txtColor").value;
var style = document.getElementById("lstStyles").value;
var msg = document.getElementById("msg");

msg.innerHTML = "Sample Text".fontsize(size).fontcolor(color);

if(style=="bold") {
msg.innerHTML = "Sample
Text".fontsize(size).fontcolor(color).bold();
} else {
msg.innerHTML = "Sample
Text".fontsize(size).fontcolor(color).italics();
}
}
</script>
</head>
<body>
<dl>
<dt>Choose Formats</dt>
<dd>
<label>Font Color</label> <input type="color" id="txtColor">
</dd>
<dd>
<label>Font Style</label> <select id="lstStyles"> <option
value="bold">Bold</option> <option value="italic">Italic</option> </select>
</dd>
<dd>
<label>Fotn Size</label> <input id="txtFontSize" type="range" min="1"
max="7" value="3">
</dd>
<dd> <button onclick="ApplyClick()">Apply</button> </dd>
</dl>
<p id="msg" align="center">Sample Text</p>
</body>
</html>

String Manipulation Properties & Methods:

1. length : It returns the total number of chars in a string.

Syntax:
var msg = "Welcome";
msg.length; // 7

Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>String</title>
<script>
function VerifyName(){
var userName = document.getElementById("txtName").value;
var error = document.getElementById("lblNameError");
if(userName.length==0) {
error.innerHTML = "User Name Required".fontcolor('red');
} else {
if(userName.length<4) {
error.innerHTML = "Name too short".fontcolor('red');
} else {
error.innerHTML = "";
}
}
}

function VerifyComments(){
var comments = document.getElementById("txtComments").value;
var commentsLength = comments.length;
var maxlength = 100;
document.getElementById("lblCount").innerHTML = `${(maxlength-
commentsLength)} chars remaining`;
}
</script>
</head>
<body>
<dl>
<dt>User Name</dt>
<dd><input type="text" id="txtName" onkeyup="VerifyName()"></dd>
<dd id="lblNameError"></dd>
<dt>Your Comments</dt>
<dd>
<textarea onkeyup="VerifyComments()" rows="4" cols="40" maxlength="100"
id="txtComments"></textarea>
</dd>
<dd id="lblCount">Max 100 chars only</dd>
</dl>
</body>
</html>

2. charAt() : It returns the character at specified index.

Syntax:
var msg = "Welcome";
msg.charAt(0); // W
msg.charAt(1); // e

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 VerifyTitle(){
var title = document.getElementById("txtTitle").value;
var msg = document.getElementById("msg");
if(title.charAt(0)=="W") {
msg.innerHTML="";
} else {
msg.innerHTML="Title must start with W character";
}
}
</script>
</head>
<body>
<dl>
<dt>Title</dt>
<dd><input type="text" id="txtTitle" onblur="VerifyTitle()"></dd>
<dd id="msg"></dd>
</dl>
</body>
</html>

3. charCodeAt() : It returns ASCII code of character at specified index.


A = 65, Z=90
a = 97, z=122

Syntax:
var msg = "Welcome";
msg.charCodeAt(0); // 87
msg.charCodeAt(1); // 101

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 VerifyTitle(){
var title = document.getElementById("txtTitle").value;
var msg = document.getElementById("msg");
var firstCharCode = title.charCodeAt(0);
console.log(firstCharCode);
if(firstCharCode>=65 && firstCharCode<=90) {
msg.innerHTML = "";
} else {
msg.innerHTML = "Title must start with uppercase
letter".fontcolor('red');
}
}
</script>
</head>
<body>
<dl>
<dt>Title</dt>
<dd><input type="text" id="txtTitle" onblur="VerifyTitle()"></dd>
<dd id="msg"></dd>
</dl>
</body>
</html>

11 ...

1. length
2. charAt()
3. charCodeAt()
4. startsWith() : It returns Boolean true if string starts with
specified char(s).
5. endsWith() : It returns Boolean true if string ends with specified
char(s).

Syntax:
var str = "Welcome to JavaScript";
str.startsWith("JavaScript"); false
str.endsWith("JavaScript"); true

Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>String</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<script>
function VerifyCard(){
var card = document.getElementById("txtCard").value;
var imgCard = document.getElementById("imgCard");

if(card.startsWith("4455")) {
imgCard.src = "../public/images/visa.jpg";
} else {
imgCard.src = "../public/images/master.jpg";
}
}
function VerifySkype(){
var skype = document.getElementById("txtSkype").value;
var lblError = document.getElementById("lblError");
if(skype.endsWith("outlook.com")) {
lblError.innerHTML = "Skype Verified".fontcolor('green');
} else {
lblError.innerHTML = "Invalid Skype Account".fontcolor('red');
}
}
</script>
</head>
<body class="container-fluid">
<dl class="mt-4 w-25">
<dt>Your Card</dt>
<dd class="input-group"> <input type="text" onkeyup="VerifyCard()"
class="form-control" id="txtCard" maxlength="16"> <img class="input-group-text"
width="70" id="imgCard"> </dd>
<dt>Your Skype Id</dt>
<dd> <input type="text" onblur="VerifySkype()" id="txtSkype" class="form-
control" placeholder="profile@outlook.com"></dd>
<dd id="lblError"></dd>
</dl>
</body>
</html>

6. indexOf() : It returns the index number of specified character in a


string.
It returns first occurrence index number.
It returns "-1" if character not found.

Syntax:
var str = "Welcome";
str.indexOf("a"); // -1
str.indexOf("e"); // 1

7. lastIndexOf() : It returns the last occurrence index number of specified


character
in a string.

Syntax:
var str = "Welcome";
str.lastIndexOf("e"); // 6

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 = document.getElementById("txtEmail").value;
var lblError = document.getElementById("lblError");
var atPos = email.indexOf("@");
var dotPos = email.lastIndexOf(".");
if(atPos<3 || (dotPos-atPos)<3) {
lblError.innerHTML = "Invalid Email".fontcolor('red');
} else {
lblError.innerHTML = "Email Verified".fontcolor('green');
}
}
</script>
</head>
<body>
<dl>
<dt>Your Email</dt>
<dd><input type="text" onblur="VerifyEmail()" id="txtEmail"></dd>
<dd id="lblError"></dd>
</dl>
</body>
</html>

8. replace() : It is used to replace a char(s) with another. [first


occurrence]

9. replaceAll() : It is used to replace all char(s) with another. [all


occurrences]

Syntax:
var str = "ES6 handles DOM. ES6 manages BOM".
str.replace("ES6", "JavaScript");
str.replaceAll("ES6", JavaScript");

Ex:
<script>
var str = "ES6 is used to manipulate DOM. ES6 handles BOM";
var result = str.replaceAll("ES6", "JavaScript");
document.write(result);
</script>
10. match() : It verifies the value with a regular expression and returns
true if
value is matching the pattern.
JavaScript regular expression is enclosed in /regExp/.

Ex:
<script>
var mobile = prompt("Enter Mobile Number");
var regExp = /\+91\d{10}/;

if(mobile.match(regExp))
{
document.write("Mobile Verified");
} else {
document.write("Invalid Mobile: Must start with +91 & 10 digits");
}
</script>

12 ....

Ex: Match

<!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/bootstrap.css">
<script type="text/javascript">
var regExp = / /;
var tip = "";
function CountryChange(){
var countryName = document.getElementById("lstCountries").value;
var imgFlag = document.getElementById("imgFlag");
if(countryName=="India") {
regExp = /\+91\d{10}/;
tip = "eg: +91 and 10 digits";
imgFlag.src= "../public/images/india.png";
} else if(countryName=="US") {
regExp = /\+\(1\)\(\d{3}\)\s\d{3}-\d{4}/;
tip = "eg: +(1)(000) 000-0000";
imgFlag.src= "../public/images/us.png";
} else if(countryName=="UK") {
regExp = /\+\(44\)\(\d{3}\)\s\d{4}\s\d{4}/;
tip = "eg: +(44)(000) 0000 0000";
imgFlag.src= "../public/images/uk.png";
} else {
regExp = / /;
tip = "Please select your country";
imgFlag.src= "";
imgFlag.alt = "N/A";
}
document.getElementById("txtMobile").placeholder = tip;
}
function VerifyClick(){
var mobile = document.getElementById("txtMobile").value;
if(mobile.match(regExp)) {
document.write("<h2>Mobile Verified..</h2>");
} else {
document.getElementById("lblError").innerHTML = `Invalid Mobile : $
{tip}`;
}

}
</script>
</head>
<body class="container-fluid">
<dl class="w-25 mt-4">
<h3>Verfiy Your Mobile <img id="imgFlag" width="50"> </h3>
<dt>Select Country </dt>
<dd>
<select class="form-select" id="lstCountries"
onchange="CountryChange()">
<option>Select Your Country</option>
<option>India</option>
<option>US</option>
<option>UK</option>
</select>
</dd>
<dt>Mobile Number</dt>
<dd><input type="text" class="form-control" id="txtMobile"></dd>
<dd id="lblError" class="text-danger"></dd>
<button class="btn btn-warning w-100"
onclick="VerifyClick()">Verify</button>
</dl>
</body>
</html>

11. slice() : It extracts the chars between the defined start and end index.

Syntax:
str.slice(startIndex, endIndex); // between index
str.slice(startIndex); // from start up to end

End index must be a value greater than start index.

Syntax:
str.slice(1, 7);
str.slice(1);

12. substr() : It extracts specified number of chars from defined start index.
It can be unidirectional i.e is can't read backward only forward.

Syntax:
str.substr(1,7); // from 1 it can read 7 chars
str.substr(7,2); // from 7 index it can read 2 chars
str.substr(1); // from 1 up to end

13. substring() : It extracts the chars between specified index with a bi-
directional
access. It can refers the index forward or backward from specified
position.

Syntax:
str.substring(1,7); // from 1 index up to 7 index
str.substring(7,1); // from 7 index up to 1 index
str.substring(1); // from 1 up to end

Ex:
<script>
var email = prompt("Enter Your Email"); // somename@gmail.com
var id = email.substring(0, email.indexOf("@"));
var domain = email.substring(email.indexOf("@")+1);
document.write(`Your Id: ${id}<br>Domain: ${domain}`);
</script>

14. trim() : It removes the leading spaces before and after the string.

15. trimStart() : It removes the leading spaces before the string.

16. trimEnd() : It removes the leadings space after the string.

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 otp = document.getElementById("txtOtp").value;
if(otp.trim()=="2345") {
document.write("Success..");
} else {
alert("Invalid OTP");
}
}
</script>
</head>
<body>
OTP : <input type="text" id="txtOtp"> <button
onclick="SubmitClick()">Submit</button>
</body>
</html>

17. split() : It splits the string at specified char and returns an array of
string.

Syntax:
var contacts = "john-987654321, david-8855323422";
var result = contacts.split(',');
document.write(result[0]); // John Details
document.write(result[1]); // David details

Ex:
<script>
var contacts = "john-9876543210, david-8855323422";
var result = contacts.split(',');
var [john, david] = result;
document.write(john.split('-')[1] + "<br>");
document.write(david.split('-')[1]);
</script>

Boolean Types

13 ...

Primitive Types:
Number
String

Boolean
- Boolean is used in decision making.
- JS Boolean can handle the values "true" & "false".
- JS Boolean can use 1 for true and 0 for false.

Syntax:
var stock = true;

if(stock==1) // valid but not recommended


{
}

if(stock==true) // good
{
}

- HTML provides various Boolean attributes for elements that use true of false
dynamically in JavaScript.

required
readonly
disabled
checked
selected

- The default value for Boolean properties is "true" you can change dynamically by
using script.

Syntax:
<button disabled> Submit </button>

document.querySelector("button").disabled = 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>
function handleChange(){
var requiredCheckbox = document.getElementById("optRequired");
var txtName = document.getElementById("txtName");
if(requiredCheckbox.checked) {
txtName.required = true;
} else {
txtName.required = false;
}

}
function termsChange(){
var termsCheckbox = document.getElementById("optTerms");
var btnSubmit = document.getElementById("btnSubmit");
if(termsCheckbox.checked) {
btnSubmit.disabled = false;
} else {
btnSubmit.disabled = true;
}
}
</script>
</head>
<body>
<form>
<dl>
<dt>User Name</dt>
<dd><input type="text" name="UserName" id="txtName"> <input
type="checkbox" onchange="handleChange()" id="optRequired"> required </dd>
<dt>Terms of Service</dt>
<dd>
<textarea rows="4" cols="40" disabled>Lorem ipsum dolor sit amet
consectetur, adipisicing elit. Nemo, tenetur impedit facere atque perspiciatis
ipsam delectus accusantium modi vel, ipsa cupiditate obcaecati sint cum veritatis
voluptates in doloremque, a debitis.</textarea>
</dd>
<dd><input type="checkbox" id="optTerms" onchange="termsChange()">
<label> I Accept </label> </dd>
</dl>
<button id="btnSubmit" disabled>Submit</button>
</form>
</body>
</html>

- Boolean operations require comparison operators and logical operators

Comparison Operators:

== Equal
=== Identical Equal
!= Not Equal
!== Not Identical
> Greater than
>= Greater than or equal
< Less than
<= Less than or equal

Logical Operators

&& AND
| | OR
! NOT

FAQ: What is difference between "==" & "===" ?


Ans: "==" can compare values of different data types.
"===" can compare only the values of same data type. It always returns false
if
you are comparing different types.

Syntax:
"10" == 10 => true
"10" === 10 => false
10 === 10 => true
"10" === "10" => true

FAQ: What is the role of Logical operators?


Ans: A local operator can evaluate value from one or multiple expressions.

Syntax:
condition1 && condition2 => returns true only when both conditions are true
condition1 || condition2 => returns true if any one condition is true.
!true => false
!undefined => defined
!null => not null, have a value

- Boolean types require selection statements to handle decision making.


- Selection statements are configured by using
if, else, switch, case, default
- Selection can be handled by using special operator "?:" ternary operator.

Ternary Operator:
- It is a JS special operator.
- It can handle operations using 3 operands.

(condition) ? true : 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/bootstrap-
icons.css">
<script>
function SortClick(){
var sortButton = document.getElementById("btnSort");
sortButton.className = (sortButton.className==="bi bi-sort-alpha-
down")? "bi bi-sort-alpha-up": "bi bi-sort-alpha-down";
}
function StockChange(){
var stockCheckbox = document.getElementById("optStock");
var lblStock = document.getElementById("lblStock");

lblStock.innerHTML = (stockCheckbox.checked)?"Available":"Out of
Stock";
}
function ShowToggle(){
var btnShow = document.getElementById("btnShow");
btnShow.innerHTML = (btnShow.innerHTML==="Show")?"Hide":"Show";
}
</script>
</head>
<body>
<button class="bi bi-sort-alpha-down" id="btnSort"
onclick="SortClick()"></button>

<div>
<input type="checkbox" onchange="StockChange()" id="optStock"> <label
id="lblStock"> Out of Stock </label>
</div>

<div>
<button onclick="ShowToggle()" id="btnShow">Show</button>
</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>
<link rel="stylesheet" href="../node_modules/bootstrap-icons/font/bootstrap-
icons.css">
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<script>
function Toggle(){
var q1 = document.getElementById("q1");
q1.style.display = (q1.style.display=="none")?"block":"none";

var lblIcon = document.getElementById("lblIcon");


lblIcon.className = (lblIcon.className==="bi bi-plus")?"bi bi-dash":"bi
bi-plus";
}
</script>
</head>
<body class="container-fluid">
<h2>FAQ's</h2>
<button onclick="Toggle()" class="d-flex w-100 btn btn-dark justify-content-
between"> <span>What is Netflix?</span> <span id="lblIcon" class="bi
bi-plus"></span> </button>
<p class="p-2" align="justify" id="q1" style="display: none;">
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Aperiam,
molestias perferendis doloremque harum explicabo nam sapiente quia dolor libero
repellendus repudiandae maiores veritatis iure error iste incidunt aliquam,
consequatur eaque.
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Itaque omnis
deserunt soluta fuga facere nihil id eos atque perferendis voluptates tenetur
inventore nemo deleniti harum, nobis asperiores fugit quae unde?
</p>
</body>
</html>

14 ....

Selection Statements
- Selection statements are used in decision making.
- Usually statements control the execution flow.
- Decision making in execution flow is managed by using
if, else, switch, case, default
The IF statement:
- It is a decision making statement used to handle a set of statements based on the
given condition.
- It have various forms
a) Forward Jump
b) Simple Decision
c) Multi Level Decisions
d) Multiple Decisions [Choices]

1. Forward Jump:
- It is a decision making approach where the statements are executed only when the
condition evaluates to true.
- It will not provide any alternative approach.

Syntax:
if (condition)
{
statements_on_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>
<script>
function VerifyCard(){
var card = document.getElementById("txtCard").value;
if(card==="4444555566667890") {
document.getElementById("txtCvv").disabled = false;
}
}
function VerifyCvv(){
var cvv = document.getElementById("txtCvv").value;
if(cvv==="3456") {
document.getElementById("lstExpiry").disabled = false;
}
}
function VerifyExpiry(){
var expiry = document.getElementById("lstExpiry").value;
if(expiry==="2025") {
document.getElementById("btnSubmit").disabled = false;
}
}
</script>
</head>
<body>
<fieldset>
<legend>Payment Details</legend>
<dl>
<dt>Card Number</dt>
<dd><input type="text" id="txtCard" onblur="VerifyCard()"
maxlength="16"></dd>
<dt>CVV</dt>
<dd><input type="text" onblur="VerifyCvv()" disabled id="txtCvv"
size="4" maxlength="4"></dd>
<dt>Expiry</dt>
<dd>
<select id="lstExpiry" onchange="VerifyExpiry()" disabled>
<option>Select Expiry Year</option>
<option>2024</option>
<option>2025</option>
<option>2026</option>
</select>
</dd>
</dl>
<button id="btnSubmit" disabled>Submit</button>
</fieldset>
</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 VerifyCard(){
var card = document.getElementById("txtCard").value;
if(card==="4444555566667890") {
document.getElementById("txtCvv").disabled = false;
document.getElementById("cvvContainer").style.display =
"block";
}
}
function VerifyCvv(){
var cvv = document.getElementById("txtCvv").value;
if(cvv==="3456") {
document.getElementById("lstExpiry").disabled = false;
document.getElementById("expiryContainer").style.display = "block";
}
}
function VerifyExpiry(){
var expiry = document.getElementById("lstExpiry").value;
if(expiry==="2025") {
document.getElementById("btnSubmit").disabled = false;
document.getElementById("btnSubmit").style.display = "block";
}
}
</script>
</head>
<body>
<fieldset>
<legend>Payment Details</legend>
<dl>
<dt>Card Number</dt>
<dd><input type="text" id="txtCard" onblur="VerifyCard()"
maxlength="16"></dd>
<div id="cvvContainer" style="display: none;">
<dt>CVV</dt>
<dd><input type="text" onblur="VerifyCvv()" disabled id="txtCvv"
size="4" maxlength="4"></dd>
</div>
<div id="expiryContainer" style="display: none;">
<dt>Expiry</dt>
<dd>
<select id="lstExpiry" onchange="VerifyExpiry()" disabled>
<option>Select Expiry Year</option>
<option>2024</option>
<option>2025</option>
<option>2026</option>
</select>
</dd>
</div>
</dl>
<button id="btnSubmit" style="display: none;" disabled>Submit</button>
</fieldset>
</body>
</html>

2. Simple Decision
- It provides one alternative to execute when condition is not satisfied.

Syntax:
if (condition)
{
statements_on_true;
}
else
{
statements_on_false;
}

- In simple decision alternative is defined by using "else" clause.


[ If � else clause ]

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 VerifyCard(){
var card = document.getElementById("txtCard").value;
if(card==="4444555566667890") {
document.getElementById("txtCvv").disabled = false;
document.getElementById("cvvContainer").style.display =
"block";
} else {
document.getElementById("btnSubmit").disabled = true;
}
}
function VerifyCvv(){
var cvv = document.getElementById("txtCvv").value;
if(cvv==="3456") {
document.getElementById("lstExpiry").disabled = false;
document.getElementById("expiryContainer").style.display = "block";
} else {
document.getElementById("btnSubmit").disabled = true;
}
}
function VerifyExpiry(){
var expiry = document.getElementById("lstExpiry").value;
if(expiry==="2025") {
document.getElementById("btnSubmit").disabled = false;
document.getElementById("btnSubmit").style.display = "block";
} else {
document.getElementById("btnSubmit").disabled = true;
}
}
</script>
</head>
<body>
<fieldset>
<legend>Payment Details</legend>
<dl>
<dt>Card Number</dt>
<dd><input type="text" id="txtCard" onblur="VerifyCard()"
maxlength="16"></dd>
<div id="cvvContainer" style="display: none;">
<dt>CVV</dt>
<dd><input type="text" onblur="VerifyCvv()" disabled id="txtCvv"
size="4" maxlength="4"></dd>
</div>
<div id="expiryContainer" style="display: none;">
<dt>Expiry</dt>
<dd>
<select id="lstExpiry" onchange="VerifyExpiry()" disabled>
<option>Select Expiry Year</option>
<option>2024</option>
<option>2025</option>
<option>2026</option>
</select>
</dd>
</div>
</dl>
<button id="btnSubmit" style="display: none;" disabled>Submit</button>
</fieldset>
</body>
</html>

Note: Checking multiple conditions using logical operators is not recommended when
you have to handle different alternatives.

3. Multi Level Decisions:


- It allows to configure conditions in a nested approach.
- It moves to next only when the outer condition evaluates to true.
- It allows to report the exact issues in the conditions.
- It also implements forward jump approach is resolving the issues.

Syntax:
if(condition1)
{
if(condition2){
statements_if_both conditions_true;
}
else {
statements_if_condition2_false;
}
}
else
{
statement_on_condition1_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>
function LoginClick(){
var userName = document.getElementById("txtName").value;
var password = document.getElementById("txtPwd").value;
var msg = document.getElementById("msg");

if(userName.length===0) {
msg.innerHTML = "User Id Required".fontcolor('red');
} else {
if(userName==="john_nit") {
if(password.length===0) {
msg.innerHTML = "Password Required".fontcolor('red');
} else {
if(password==="john@123"){
document.write("Login Success");
} else {
msg.innerHTML = "Invalid Password".fontcolor('red');
}
}
} else {
msg.innerHTML = "Invalid User Id".fontcolor('red');
}
}

}
</script>
</head>
<body>
<fieldset>
<legend>User Login</legend>
<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>
<p id="msg"></p>
</fieldset>
</body>
</html>

15 ...
Selection Statements
- The IF selector
a) Forward Jump
b) Simple Decision
c) Multi Level [Nested, Ladder]
d) Multiple Choices

4. Multiple Choices
- It is the process of defining multiple conditions to handle one situation.
- It also allows to perform action individually when the matching condition
evaluates to true.
- Alternative choices are provided by using "else if".

Syntax:
if( condition-1 )
{
statements on condition-1 true;
}
else if (condition-2)
{
statements on condition-2 true;
}
else
{
statements when both conditions evaluate to 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/bootstrap.css">
<script>
var flag = "";
function ContinueClick(){
var UserId = document.getElementById("txtUserId").value;
var lblUserError = document.getElementById("lblUserError");
var idContainer = document.getElementById("idContainer");
var pwdContainer = document.getElementById("pwdContainer");
if(UserId==="+919876543210")
{
flag = `Your mobile ${UserId} verified Successfully : OTP Sent`;
idContainer.style.display = "none";
pwdContainer.style.display = "block";

}
else if(UserId==="john_nit@gmail.com")
{
flag = `Your email ${UserId} verified successfully : please click
activation link`;
idContainer.style.display = "none";
pwdContainer.style.display = "block";

} else {
lblUserError.innerHTML = `${UserId} Not Available`;
}
}
function LoginClick(){
var pwd = document.getElementById("txtPwd").value;
if(pwd==="john@11") {
document.write(flag);
} else {
document.getElementById("lblPwdError").innerHTML = "Invalid
Password";
}
}
</script>
</head>
<body class="container-fluid d-flex justify-content-center align-items-center"
style="height:100vh">
<div>
<h2>Signin</h2>
<div id="idContainer">

<label class="form-label fw-bold">Enter mobile number or Email</label>


<div>
<input type="text" id="txtUserId" class="form-control">
<div class="text-danger" id="lblUserError"></div>
</div>
<div class="mt-3">
<button onclick="ContinueClick()" class="btn btn-warning w-
100">Continue</button>
</div>
</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>
<div class="mt-3">
<button class="btn btn-warning w-100"
onclick="LoginClick()">Login</button>
</div>
</div>
</div>
</body>
</html>

Task:
1. Write a program to take 3 numbers and find the greatest among 3 numbers and
print the greatest.

function findGreatest(a, b, c)
{

// if condition

findGreatest(10, 30, 5); // b is greater than a and c


findGreatest(20,10,5); // a is greater than b and c
findGreatest(40, 0, 60); // c is greater than a and b
Ex:
<script>
function findGreatest(a, b, c)
{
if(a > b && a > c)
{
document.write(`a=${a} is greater than b=${b} & c=${c}`);
}
else if(b > c) {
document.write(`b=${b} is greater than a=${a} & c=${c}`);
} else {
document.write(`c=${c} is greater than a=${a} & b=${b}`);
}
}
findGreatest(130, 210, 40);
</script>

2. Write a program to find the value range.

function findRange(value, min, max)


{
// if

findRange(2, 10, 40); // your value 2 is not in range of 10 to 40.


findRange(2, 5, 30); // your value 2 is not in range of 4 to 30.
findRange(6, 5, 30); // your value 6 is in the range of 5 to 30

Ex:
<script>
function findRange(value, min, max)
{
if(value>=min && value<=max) {
document.write(`Your value ${value} is in range of ${min} & ${max}`);
} else {
document.write(`Your value ${value} is not in range of ${min} & $
{max}`);
}

}
findRange(25, 5, 20);
</script>

3. Check if a triangle is equilateral, scalene, or isosceles

function findTriangleType(side1, side2, side3)


{

findTriangleType(12,12,12) //"Equilateral triangle."


findTriangleType(20,20,31) //"Isosceles triangle."
findTriangleType(5,4,3) //"Scalene triangle."

Ex:
<script>
function findTriangleType(side1, side2, side3) {
if((side1 == side2) && (side1 == side3)){
console.log(`Equilateral triangle.`)
}
else if ((side1 == side2) || (side2 == side3) || (side1 == side3)){
console.log(`Isosceles triangle.`)
}
else{
console.log(`Scalene triangle.`)
}
}

</script>

Switch

You might also like