JAVASCRIPT
JAVASCRIPT
JAVASCRIPT
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:
"use strict";
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>
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>
Syntax:
<body>
<noscript>
Please enable JS on your browser.
</noscript>
</body>
Ex:
1. Add a new script file into scripts folder
"ticket.js"
"use strict";
function PrintPage() {
window.print();
}
<head>
<script type="text/javascript" src="../src/scripts/ticket.js"> </script>
</head>
<body>
<button onclick="PrintPage()"> Print </button>
</body>
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....
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>
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>
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>
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>
Syntax:
<p> </p>
innerHTML:
- It is similar to innerText and textContent but allows all rich formats with
markup.
Syntax:
document.querySelector("p").innerHTML = "Some text | <markup> </markup>";
outerHTML:
- It is similar to innerHTML but can replace the existing element with new element.
Syntax:
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.....
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.
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 �
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");
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>
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;
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.
a) Declaration
b) Assignment
c) Initialization
a) var
b) let
c) const
var x ;
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
- 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.
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 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;
document.write("x=" + x); // x = undefined
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
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>
Syntax:
var [x, y, z]; // invalid
Syntax:
var [x,y,z] = [ ];
x = 10;
y = 20; => valid
z = 30;
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
a) toFixed(fractions)
Syntax:
var price = 45000.00;
Syntax:
document.write("Price=" + price.toLocaleString("en-in", { style:"currency",
currency:"INR"})
Ex:
<script>
var price = 450000.45 + 5000;
a) parseInt()
b) parseFloat()
Syntax:
var age = "22";
parseInt(age);
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"));
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
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>
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;
}
</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 ₹ <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>₹ 1,00,000</span>
<span>₹ 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>
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 "${ }"
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>
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
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();
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>
<!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");
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>
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>
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>
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>
Syntax:
var str = "Welcome";
str.indexOf("a"); // -1
str.indexOf("e"); // 1
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>
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
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.
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==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>
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
Syntax:
"10" == 10 => true
"10" === 10 => false
10 === 10 => true
"10" === "10" => true
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
Ternary Operator:
- It is a JS special operator.
- It can handle operations using 3 operands.
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";
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;
}
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.
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">
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
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>
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