Javascript
Javascript
Page -1
What is JavaScript?
- JavaScript handles
c) Validation etc.
- BOM Interactions
a) Window Manipulations
b) Location
c) History
- DOM Interactions
a) Data Binding
b) Style Binding
c) Class Binding
x = 10; // number
“use strict”;
- Limited extensibility.
Evolution of JavaScript:
- CERN labs developed a script called ECMA Script for Mosaic Browser.
1994-1995.
1. Inline
2. Embedded
3. External File
JavaScript Inline
- You can write JavaScript functions directly for HTML element in design.
- It is faster in interactions.
Syntax:
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>Your Ticket</h1>
<button onclick="[Link]()">Print</button>
</body>
</html>
Page -2
1. Inline
2. Embedded
3. External File
JavaScript Inline
- You can configure JavaScript function directly for any element in design.
- It is faster in interactions.
Syntax:
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>Your Ticket</h1>
<button onclick="[Link]()">Print</button>
</body>
</html>
JavaScript Embedded
- JavaScript functions are written in a <script> container and embedded into <head> or <body>
Syntax:
<script>
function PrintPage()
[Link]();
</script>
- You can turn ON strict mode in embed or external file by using “use strict”.
<script type=“text/javascript”>
“use strict”;
… your functions …
</script>
- You can target script for legacy browsers by enclosing the code in HTML comment block.
<!--
function Name()
-->
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript">
"use strict";
<!--
function PrintPage() {
[Link]();
-->
</script>
</head>
<body>
<h1>Your Ticket</h1>
<button onclick="PrintPage()">Print</button>
</body>
</html>
JavaScript from External File:
- You can write JavaScript functions in a separate script file with extension “.js”
- However external files will increase number of requests and also page load time.
Ex:
1. Src/scripts/[Link]
"use strict";
function PrintPage() {
[Link]();
2. Js-examples/[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</script>
</head>
<body>
<h1>Your Ticket</h1>
<button onclick="PrintPage()">Print</button>
</body>
</html>
- JavaScript selects HTML elements to transform static DOM into dynamic DOM.
- There are various reference techniques to refer and select elements in page.
- However referring DOM uses an index of element, which need to be updated every time
when element changes position in design.
Syntax:
[Link][index].property = value;
[Link][index].elements[index].property = value;
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function bodyload(){
[Link][0].src = "../public/images/[Link]";
[Link][0].elements[1].value = "Login";
[Link][1].elements[2].value = "Register";
</script>
</head>
<body onload="bodyload()">
<div>
</div>
<div>
<form>
<h3>Login</h3>
</form>
</div>
<div>
<form>
<h3>Register</h3>
<br><br>
<br><br>
<input type="button">
</form>
</div>
</body>
</html>
2. Refer by using name
- You can’t refer any generic child element directly without referring to its parent.
- HTML can define same name for multiple elements, which will lead to reference issued in JavaScript.
Syntax:
<img name=“poster”>
<form name=“frm”>
</form>
[Link]=“path”;
[Link] = “value”;
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script>
function bodyload(){
[Link]="../public/images/[Link]";
[Link] = "Login";
[Link] = "Register";
</script>
</head>
<body onload="bodyload()">
<div>
</div>
<div>
<form name="frmLogin">
<h3>Login</h3>
</form>
</div>
<div>
<form name="frmRegister">
<h3>Register</h3>
<input type="text" placeholder="User Name">
<br><br>
<br><br>
</form>
</div>
</body>
</html>
3. Refer by using ID
by using ID.
- It can directly access element from any level of hierarchy without referring to parent.
- ID is a reference used for styles in CSS, which can conflict with JavaScript reference.
Syntax:
<img id=“poster”>
[Link](“poster”).src = “path”;
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function bodyload(){
[Link]("poster").src="../public/images/[Link]";
[Link]("btnLogin").value = "Login";
[Link]("btnRegister").value="Register";
</script>
</head>
<body onload="bodyload()">
<div>
</div>
<div>
<form name="frmLogin">
<h3>Login</h3>
</form>
</div>
<div>
<form name="frmRegister">
<h3>Register</h3>
<br><br>
<br><br>
</form>
</div>
</body>
</html>
a) Relational
b) Attribute
c) Primary etc.
Syntax:
<img>
[Link](“img”).property = value;
[Link](“#btnLogin”).property = value;
[Link](“.btn-primary”).property = value;
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function bodyload(){
[Link]("img").src="../public/images/[Link]";
[Link]("#btnLogin").value = "Login";
[Link](".btn-register").value = "Register";
</script>
</head>
<body onload="bodyload()">
<div>
</div>
<div>
<form name="frmLogin">
<h3>Login</h3>
</form>
</div>
<div>
<form name="frmRegister">
<h3>Register</h3>
<br><br>
</form>
</div>
</body>
</html>
Page- 3
a) [Link]() b) [Link]()
c) [Link]() etc.
1. alert()
2. confirm()
3. [Link]()
4. textContent
5. innerText
6. innerHTML
7. outerHTML
8. console methods
alert()
- It will not allow to perform any another task in page until or unless you confirm.
Syntax:
alert(“message | expression”);
Ex:
alert(“Welcome”);
alert( 10 + 20 );
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function DeleteClick(){
</script>
</head>
<body>
<button onclick="DeleteClick()">Delete</button>
</body>
</html>
confirm()
true : on OK
false : on Cancel
Syntax:
confirm(“message | expression”);
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function DeleteClick(){
alert("Deleted..");
} else {
alert("Canceled..");
</script>
</head>
<body>
<button onclick="DeleteClick()">Delete</button>
</body>
</html>
[Link]()
Syntax:
[Link](“message | expression | markup”);
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function DeleteClick(){
if(choice==true){
} else {
alert("Canceled..");
</script>
</head>
<body>
<button onclick="DeleteClick()">Delete</button>
</body>
</html>
- Both techniques are similar and used to present output into any container element in
page.
- innerText is deprecated.
- The container element must be an HTML element that can present text
- Both are RC type, they will not allow complex formats for content.
Syntax:
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function DeleteClick(){
if(choice==true){
} else {
[Link]("p").textContent = "Canceled..";
</script>
</head>
<body>
<button onclick="DeleteClick()">Delete</button>
<p></p>
</body>
</html>
innerHTML
Syntax:
outerHTML
- It is similar to innerHTML but can replace the target element with current element
defined in markup.
Syntax:
<p>
</p>
[Link](“p”).outerHTML = “<h1> Welcome </h1>”
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function DeleteClick(){
if(choice==true){
} else {
[Link]("p").outerHTML = "<h1>Canceled</h1>";
</script>
</head>
<body>
<button onclick="DeleteClick()">Delete</button>
<p></p>
</body>
</html>
Console Methods
[Link]()
[Link]()
[Link]()
[Link]()
[Link]() etc.
Syntax:
Ex:
[Link](“line-1 \n line-2”);
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function DeleteClick(){
[Link]("Delete Clicked");
if(choice==true){
} else {
[Link]("p").outerHTML = "<h1>Canceled</h1>";
[Link]("Cancel button clicked");
[Link]("Log message");
</script>
</head>
<body>
<button onclick="DeleteClick()">Delete</button>
<p></p>
</body>
</html>
Page -4
- User can provide a value to application, which is scanned and used for processing.
- JavaScript allows user to input a value into webpage by using following techniques
1. Query String
2. prompt()
3. Form elements
Query String
- “location” is a browser object and “search” is a property to read query string from browser.
- You can convert the query string into a collection by using “URLSearchParams()”.
Syntax:
[Link]()
[Link]()
[Link]
[Link]()
[Link]()
[Link]() etc.
Ex: [Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function bodyload(){
}
</script>
</head>
<body onload="bodyload()">
<h2>Search Results</h2>
<p></p>
</body>
</html>
URL: [Link]
Ex:
1. [Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h3>Add Product</h3>
<form method="get" action="./[Link]">
<dl>
<dt>Name</dt>
<dt>Price</dt>
<dt>Category</dt>
<dd>
<select name="Category">
<option>Select Category</option>
<option>Electronics</option>
<option>Fashion</option>
</select>
</dd>
</dl>
</form>
</body>
</html>
2. [Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
dt {
font-weight: bold;
margin-bottom: 10px;
dd {
margin-bottom: 10px;
dl {
display: grid;
font-family: Arial;
</style>
<script>
function bodyload(){
[Link]("lblName").textContent = [Link]("Name");
[Link]("lblPrice").textContent = [Link]("Price");
[Link]("lblCategory").textContent = [Link]("Category");
</script>
</head>
<body onload="bodyload()">
<h2>Product Details</h2>
<dl>
<dt>Name</dt>
<dd id="lblName"></dd>
<dt>Price</dt>
<dd id="lblPrice"></dd>
<dt>Category</dt>
<dd id="lblCategory"></dd>
</dl>
<br><br>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function AddClick(){
</script>
</head>
<body>
<p></p>
</body>
</html>
prompt() :
Syntax:
prompt(“message”, “default_value”);
Syntax:
if (data==null)
{
// action on cancel
else if (data==‘ ’)
// action on empty
else
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function AddClick(){
if(data==''){
alert('Please provide a folder name');
} else if(data==null){
alert('You canceled..');
} else {
</script>
</head>
<body>
<p></p>
</body>
</html>
- HTML form provides various input elements like textbox, checkbox, radio, dropdown,
- JavaScript can handle input directly from form elements by accessing their values.
Syntax:
<input type=“text” id=“txtName”>
<select id=“lstCategories”>
[Link](“txtName”).value
[Link](“lstCategories”).value
Page-5
- User can provide a value to application, which is scanned and used for processing.
- JavaScript allows user to input a value into webpage by using following techniques
1. Query String
2. prompt()
3. Form elements
Query String
- “location” is a browser object and “search” is a property to read query string from browser.
- You can convert the query string into a collection by using “URLSearchParams()”.
Syntax:
[Link]()
[Link]()
[Link]
[Link]()
[Link]()
[Link]() etc.
Ex: [Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function bodyload(){
</script>
</head>
<body onload="bodyload()">
<h2>Search Results</h2>
<p></p>
</body>
</html>
URL: [Link]
Ex:
1. [Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h3>Add Product</h3>
<dl>
<dt>Name</dt>
<dt>Price</dt>
<dt>Category</dt>
<dd>
<select name="Category">
<option>Select Category</option>
<option>Electronics</option>
<option>Fashion</option>
</select>
</dd>
</dl>
</form>
</body>
</html>
2. [Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
dt {
font-weight: bold;
margin-bottom: 10px;
dd {
margin-bottom: 10px;
dl {
display: grid;
font-family: Arial;
</style>
<script>
function bodyload(){
[Link]("lblName").textContent = [Link]("Name");
[Link]("lblPrice").textContent = [Link]("Price");
[Link]("lblCategory").textContent = [Link]("Category");
</script>
</head>
<body onload="bodyload()">
<h2>Product Details</h2>
<dl>
<dt>Name</dt>
<dd id="lblName"></dd>
<dt>Price</dt>
<dd id="lblPrice"></dd>
<dt>Category</dt>
<dd id="lblCategory"></dd>
</dl>
<br><br>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script>
function AddClick(){
</script>
</head>
<body>
<p></p>
</body>
</html>
prompt() :
Syntax:
prompt(“message”, “default_value”);
- Prompt returns the following
Syntax:
if (data==null)
// action on cancel
else if (data==‘ ’)
// action on empty
else
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function AddClick(){
if(data==''){
} else if(data==null){
alert('You canceled..');
} else {
</script>
</head>
<body>
<p></p>
</body>
</html>
- HTML form provides various input elements like textbox, checkbox, radio, dropdown,
- JavaScript can handle input directly from form elements by accessing their values.
Syntax:
<select id=“lstCategories”>
[Link](“txtName”).value
[Link](“lstCategories”).value
Page -6
Summary
- Variable
- Declaration
- Assignment
- Initialization
Var keyword:
- You can declare or initialize in any block and access from any another block.
- It allows shadowing.
- Shadowing is the process of re-declaring or re-initializing same name identifier with in the
scope.
x=20; // assignment
Ex:
<script>
function f1()
{
var x; // declaration
x = 10; // assignment
if(x==10)
y = 30; // assignment
f1();
</script>
- It allows hoisting.
- Hoisting allows to use and declare variables without any order dependency.
Syntax:
<script>
“use strict”;
x = 10;
[Link](x);
var x; // hoisting
</script>
Let Keyword:
- Block scope allows to access in the same block and in its inner blocks.
Ex:
<script>
"use strict";
function f1()
let x; // declaring
x = 10; // assignment
if(x==10)
f1();
</script>
Const Keyword:
Syntax:
- You can declare or initialize a global variable using var, let & const keywords.
- You can configure a variable inside function and make it global in access by using
“window” object.
Syntax:
[Link] = value;
Ex:
<script>
"use strict";
var x = 10;
let y = 20;
const z = 30;
function f1(){
window.a = 50;
[Link]("f1 x=" + x + "y=" + y + "z=" + z + "a=" + a + "<br>");
function f2(){
f1();
f2();
</script>
Variable Naming:
$name; // intended to refer library variable. [ library is a set of values & functions]
- It can’t be a keyword.
var class; // invalid
var product;
var products;
var productName;
var btnInsert;
- Name doesn’t have a limit for chars officially, however the max limit for chars on 64bit
var x, y, z; // valid
Page -7
- The data type in memory is determined according to the value initialized or assigned.
x = “A”; // x is string
x = true; // x is boolean
a) Primitive Types
1. Number
2. String
3. Boolean
4. Null
5. Undefined
Number Type
Signed Integer - 20
Unsigned Integer 20
Double 234.42
Decimal 2345.34
Binary 0b1010
Hexadecimal 0x0101
Octa 0o745
a) parseInt()
b) parseFloat()
parseInt(“24AB”) + 1 => 25
parseInt(“24AB25) + 1 => 25
parseInt(“10.45”) + 1 => 11
parseFloat(“10.45”) + 1 => 11.45
if (isNaN(“A”))
// not a number;
else
// is a number;
Ex:
<script>
if(isNaN(rate)){
} else {
}
</script>
a) toFixed()
[Link](2); // 45000.00
b) toPrecision()
- It can slice a number to exact precision of chars starting from first index.
[Link](7); // 45000.57
c) toLocaleString()
- It converts a number into a regional string.
[Link](); // 450,000
[Link](‘en-in’); // 4,50,000
a) currency
b) decimal
c) percent
d) unit
a) compact
b) scientific
c) metric etc.
Ex:
<script>
</script>
Ex:
<script>
var price = 450000;
</script>
Page -8
Summary
- Number Type
- Parsing Methods
a) parseInt()
b) parseFloat()
- isNaN()
- Formatting Methods
a) toFixed()
b) toPrecision()
c) toLocaleString()
- Format Style
a) currency
b) decimal
c) unit
d) percent
- Format Notation
a) scientific
b) metric
c) compact
d) engineering
String Type
a) Double Quotes “ ”
b) Single Quotes ‘ ’
c) Back Ticks ` `
- Double and Single quotes are used for outer and inner strings.
Syntax:
- Double and Single quote requires lot of concat techniques to bind dynamic values.
“string” + value + “string”;
- ES5+ version provides back tick that allows embedded expression using “${ }”.
- It is a data binding expression to bind dynamic values, but it is allowed only in string with backticks.
Ex:
<script>
var msg1 = "Hello ! " + user + " your age will be " + (age+1) + " next year.<br>";
var msg2 = `Hello ! ${user} your age will be ${age+1} next year.`;
[Link](msg1);
[Link](msg2);
</script>
- Backtick allows inner string with both double and single quotes.
Ex:
<script>
[Link](path);
</script>
bold()
italics()
strike()
sup()
sub()
fontsize()
fontcolor()
toUpperCase()
toLowerCase() etc.
- Several formatting methods are not allowed on RC type. Always use with innerHTML.
Syntax:
“string”.fontsize(‘2’).fontcolor(‘red’).bold().italics()
Events:
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function VerifyUser(){
var username = [Link]("user").value;
if(username=="david_nit"){
} else {
function ChangeCase(){
[Link]("code").value = [Link]();
</script>
</head>
<body>
<dl>
<dt>User Name</dt>
<dd id="lblMsg"></dd>
<dd>
</dl>
</body>
</html>
String Manipulation:
1. length
Syntax:
[Link]; => 7
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function VerifyUser(){
if([Link]==0){
} else {
if([Link]<4){
} else {
[Link] = "";
function VerifyComments(){
</script>
</head>
<body>
<dl>
<dt>User Name</dt>
<dd id="lblUser"></dd>
<dt>Your Comments</dt>
<dd>
</dd>
<dd id="lblStatus"></dd>
</dl>
</body>
</html>
2. charAt()
Syntax:
[Link](0); // W
[Link](6); // e
3. charCodeAt()
- Character code
A = 65, Z=90
a = 97, z=122
Syntax:
[Link](0); // 65
[Link](2); // 97
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function VerifyName(){
[Link] = "";
} else {
</script>
</head>
<body>
<dl>
<dt>User Name</dt>
<dd id="lblName"></dd>
</dl>
</body>
</html>
Page -9
String Type
- Formatting Method
- Manipulation
1. length
2. charAt()
3. charCodeAt()
4. indexOf()
5. lastIndexOf()
Syntax:
var str = “Welcome”;
[Link](“e”); // 1
[Link](“e”); // 6
[Link](“a”); // -1
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function VerifyEmail(){
if([Link]("@")==-1){
} else {
[Link] = "";
}
}
</script>
</head>
<body>
<dl>
<dt>Email</dt>
<dd id="lblEmail"></dd>
</dl>
</body>
</html>
6. startsWith()
7. endsWith()
Syntax:
[Link](“outlook”); // false
[Link](“gmail”); // true
[Link](“in”); // false
[Link](“com”); // true
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function VerifyCard(){
if([Link]("4455")){
[Link]= "../public/images/[Link]";
} else {
[Link]= "../public/images/[Link]";
}
function VerifySkype(){
if([Link]("[Link]")){
[Link] = "";
} else {
</script>
</head>
<body class="container-fluid">
<h3>Verify Details</h3>
<dl class="w-25">
<dd class="input-group">
</dd>
<dd>
</dd>
<dd id="lblSkype"></dd>
</dl>
</body>
</html>
8. slice()
Syntax:
[Link](startIndex, endIndex)
9. substr()
Syntax:
[Link](startIndex, count_of_chars);
10. substring()
Syntax:
[Link](startIndex, endIndex);
Ex:
<script>
[Link]([Link](8,0) + "<br>");
</script>
Task:
// info@[Link]
var id = [Link](0, [Link](“@“)); something_123, info
Task:
var key = ?
var value = ?
Ex:
<script>
[Link](`Key=${key}<br>Value=${value}`);
</script>
11. replace()
12. replaceAll()
Syntax:
[Link](“old”, “new”);
[Link](“old”, “new”);
Ex:
<script>
[Link]([Link]("JS", "JavaScript"));
</script>
13. trimStart()
15. trim()
Syntax:
[Link]()
[Link]()
[Link]()
Ex:
<script>
if([Link]()=="admin"){
[Link]("Login Success..");
} else {
[Link]("Invalid Password");
</script>
Page-10
16. match()
a) Meta Characters
b) Quantifiers
Syntax:
if ([Link]( / expression / )
// on true;
else
// on false;
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function VerifyPassword(){
if([Link]==0){
} else {
if([Link](regExp)){
[Link] = "100%";
} else {
if([Link]<4){
[Link] = "Poor Password".fontcolor('white');
[Link] = "30%";
} else {
[Link] = "70%";
</script>
</head>
<body class="container-fluid">
<h3>Register</h3>
<dl class="w-25">
<dt>Password</dt>
<dd>
<div class="progress">
<div class="progress-bar" id="progressBar">
<span id="lblPwd"></span>
</div>
</div>
</dd>
</dl>
</body>
</html>
17. split()
Syntax:
0 1 2
Ex:
<script>
[Link]([Link]('-')[1]);
</script>
Task :
var id = ?
var domain= ?
<script>
[Link](`Id=${id}<br>Domain=${domain}`);
</script>
18. includes()
- It is a boolean method that returns true if string contains specified chars. - It uses a search string
to verify content in element.
Syntax:
if ([Link](searchString))
{
Note: You need iterators or loops for read every element from a collection.
Syntax:
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function Search(){
[Link] = "block";
} else {
[Link] = "none";
</script>
</head>
<body>
<ul>
</ul>
</body>
</html>
Boolean Type
- JavaScript boolean can use “1” for true and “0” for false.
a) open
b) required
c) readonly
d) selected
e) checked
f) disabled etc.
Syntax:
true + true = ? 2
true + “A” = ? trueA
“A” + “B” = AB
10 + “A” = 10A
“A” * 2 = NaN
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function VerifyName(){
if([Link]==0){
[Link] = true;
} else {
[Link] = false;
}
function ToggleAds(){
if([Link]==true){
[Link] = true;
} else {
[Link] = false;
</script>
</head>
<body>
<dialog>
<h4>Ads</h4>
</dialog>
<dl>
<dt>User Name</dt>
</body>
</html>
Page-11
Summary
- Number
- String
- Boolean
Undefined:
- It is a type configured for variables which are not defined with a value.
- If variable is declared and value is not initialized or assigned then compiler sets as
“undefined”.
Syntax:
var x ;
[Link](x); x = undefined
if (x==undefined) => not good
if(x) => JS will return true if value is defined in “x” reference. // good
Ex:
<script>
var price;
if(price){
[Link](`Price=${price}`);
} else {
</script>
Null Type:
- If a reference is expecting value at compile time and it is not specified then it is set with
“undefined”.
- If a reference is expecting value at runtime and it is not specified then it return null.
Syntax:
if(name== null)
Symbol Type:
Syntax:
var id = Symbol();
var obj = {
[id] : 1
a) Array
b) Object
c) Map
Array Type:
- Array can reduce complexity by storing multiple values under one reference name.
- Few technologies may restrict array to similar type and will not allow to change size
dynamically.
- Array is a type of arrangement for values in sequential order that allows to access in
random.
Configuring Array:
1. Array requires a declaration, which you can defined using “var, let, const” keywords.
Assignment of Memory
var data;
data = [ ];
(or)
Initialization of Memory
var data = [ ];
(or)
Ans: Array constructor uses dynamic memory, which is newly allocated on every request.
[ ] meta character uses static memory, which is good for continuous operations.
Page-12
Array
Array Configuration
[]
Array()
Array Elements:
- Array is a collection of elements in sequential order.
Syntax:
let data = [ ];
Ex:
<script>
data["3"] = 20;
data[4] = false;
</script>
- Array element can be any type.
a) Primitive
b) Non Primitive
c) Function
Syntax:
data[0](); // IIFE
Ex:
<script>
var data = [1, "A", true, ['Delhi', 'Hyd'], function(){[Link]('Function in Array Memory..')}];
[Link](data[3][1] + "<br>");
data[4]();
</script>
Ex:
<script>
[Link](data[1][0][1]);
</script>
Array Manipulations:
Syntax:
[Link]();
[Link](‘ separator ’ );
Ex:
<script>
</script>
Syntax:
[Link](function(value, index) {
})
“value & index” are formal names, you can defined any name.
The first param refers to value and second refers to index.
Syntax:
Ex:
<script>
</script>
Syntax:
[Link](startIndex, endIndex);
find() : It uses a function that finds and returns the first occurrence value
filter() : It is similar to find but returns all elements that match given
condition.
Syntax:
[Link](function(value) {
return value_condition;
})
Ex:
<script>
return value>=60000;
});
[Link](result);
</script>
3. Array De-structure and Spread
Syntax:
let a = data[0];
let b = data[1];
let c = data[2];
- Spread is a new operator “…” of ES6 that allows to spread a collection into individual
elements.
Syntax:
let list3 = […list1, list2]; // list3 => have 3 elements [10, 20, list2]
let list3 = […list1, …list2]; // list3 => have 4 elements [10, 20, 30, 40]
Ex:
<script>
[Link](list3);
</script>
Page -13
Note: To add items without deleting existing the delete count must be set to “0”.
Ex:
<script>
[Link](2,0,"C","E");
[Link](function(value, index){
})
</script>
[Link]()
[Link]()
[Link](startIndex, deleteCount)
Note: You can’t sort numerical values, they are sorted as string.
[Link]().reverse()
[Link] = value;
4. Add element into page by using the method “appendChild()”. It requires a parent element to add
newly create element.
[Link](“body”).appendChild(ref);
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function UploadClick(){
[Link] = "100";
[Link] = "100";
[Link]= "../public/images/[Link]";
[Link]("container").appendChild(pic);
function MoreClick(){
[Link] = "file";
[Link] = "block";
[Link] = "10px";
[Link]("files").appendChild(input);
function bodyload(){
[Link]="1";
[Link] = "300";
var th = [Link]("th");
[Link] = "Name";
thead_tr.appendChild(th);
[Link](thead_tr);
[Link](thead);
[Link]("data").appendChild(table);
</script>
</head>
<body onload="bodyload()">
<div id="data">
</div>
<br><br>
<div id="container"></div>
<h3>File Upload</h3>
<div>
<div id="files">
</div>
</div>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
margin-top: 20px;
margin-bottom: 20px;
nav {
background-color: black;
color:white;
padding: 10px;
display: flex;
justify-content: space-around;
nav a {
color:white;
</style>
<script>
function bodyload(){
[Link](function(item){
var li = [Link]("li");
[Link] = item;
[Link]("ol").appendChild(li);
[Link] = item;
[Link] = item;
[Link]("select").appendChild(option);
var span = [Link]("span");
[Link]("nav").appendChild(span);
[Link]("ul").appendChild(ul_li);
})
[Link](function(courseImagePath){
[Link] = courseImagePath;
[Link]="100";
[Link]="100";
[Link] = "10px";
[Link]("header").appendChild(img);
})
</script>
</head>
<body onload="bodyload()">
<header>
</header>
<ol>
</ol>
<select>
</select>
<nav>
</nav>
<ul style="list-style: none; height: 50px; overflow: auto; border:1px solid gray; padding: 10px; width:
150px;">
</ul>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function bodyload(){
[Link](function(course){
[Link] = "200px";
[Link] = `
<div class="card-header">
</div>
</div>
<div class="card-footer">
</div>
`;
[Link]("section").appendChild(div);
})
</script>
</head>
<section class="d-flex">
</section>
</body>
</html>
Page -14
1. Src/scripts/[Link]
var movies = [
"dhurandhar"
];
function LoadMovies(){
[Link]("lstMovies").innerHTML = "";
[Link](function(movie){
[Link] = [Link]();
[Link] = movie;
[Link]("lstMovies").appendChild(option);
})
function AddClick(){
if([Link]([Link]())==-1){
[Link]([Link]());
alert(`${[Link]()}\nAdded Successfully..`);
LoadMovies();
[Link]("txtMovie").value = "";
} else {
alert(`${[Link]()} exists`);
function SortAsc(){
[Link]();
LoadMovies();
function SortDesc(){
[Link]();
[Link]();
LoadMovies();
}
function DeleteClick(){
if(flag==true){
[Link](selectedMovieIndex,1);
LoadMovies();
function ClearClick(){
[Link] = 0;
LoadMovies();
function EditClick(){
[Link]("txtEditMovie").value = selectedMovieName;
}
function SaveClick(){
movies[selectedMovieIndex] = editedMovieName;
LoadMovies();
2. Js-examples/[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="../node_modules/bootstrap/dist/js/[Link]"></script>
<script src="../src/scripts/[Link]"></script>
</head>
<div class="input-group">
</div>
</div>
<div class="my-2">
</div>
</select>
<div class="my-2">
</div>
<div class="my-2">
<button onclick="EditClick()" data-bs-target="#edit" data-bs-toggle="modal" class="btn btn-warning
bi bi-pen"> Edit</button>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h3>Edit Movie</h3>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Object Type
- Alan Kay introduced the concept of Object into computer programming in early 1960’s.
“key” : value,
“key” : value
- Key is accessible within object by using “this” keyword and outside object using
object name.
let tv = {
Name: “Samsung TV”,
Price: 45000,
let obj = {
key : value,
key : function(){
Ex:
<script>
let product = {
Name : "",
Price: 0,
Qty: 0,
Total : function(){
},
Print: function(){
[Link](`Name=${[Link]}<br>Price=${[Link]}<br>Qty=${[Link]}<br>Total=
${[Link]()}`);
[Link] = 45000;
[Link] = 2;
[Link]();
[Link]("<hr>");
[Link] = "iPhone";
[Link] = 70000;
[Link]();
</script>
- If object comprises of only data then it is referred as “JSON” JavaScript object notation.
Page -15
AJAX
Object Type
- Key / Values
- Relative Data
JSON
- It is a representation of data
Syntax:
{
“key”: value,
“key”: value
a) for..in
b) [Link]()
Syntax:
Ex:
<script>
var product = {
Name: "TV",
Price: 45000,
Rating: 3.5
[Link](key + "<br>");
</script>
Ex:
<script>
var product = {
Name: "TV",
Price: 45000,
Rating: 3.5
[Link](product).map(function(key){
[Link](`${key}: ${product[key]}<br>`);
})
</script>
3. You can verify the key by using “in” operator. It returns true if key is available.
4. You can know the data type of value in a key by using “typeof” operator.
JavaScript Ajax
[Link]();
1 Initial
2 Success
3 Complete
4 Ready
if ([Link] == 4)
// [Link];
// [Link];
// [Link]; etc.
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function LoadClick(){
[Link]();
[Link] = function(){
if([Link]==4){
[Link]("container").innerHTML = [Link];
function LoadMyntra(){
[Link]();
[Link] = function(){
if([Link]==4){
[Link]("frame").innerHTML = [Link];
</script>
</head>
<body>
<header>
<h1>Shopping Home</h1>
</header>
<section>
<button onclick="LoadMyntra()">Myntra</button>
<br><br>
<div id="frame"></div>
<pre id="container">
</pre>
</section>
</body>
</html>
"price": 79000,
"image": "../public/images/[Link]",
"offers": [
"Bank Offer5% cashback on Flipkart SBI Credit Card upto ₹4,000 per calendar quarterT&C",
"Bank Offer5% cashback on Flipkart Axis Bank Credit Card upto ₹4,000 per statement quarterT&C",
"Bank OfferUp To ₹50 Cashback on BHIM Payments App. Min Order Value ₹199. Offer Valid Once Per
User"
}
3. Add HTML page “[Link]”
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function bodyload(){
[Link]();
[Link] = function(){
if([Link]==4){
product = [Link]([Link]);
[Link]("imgProduct").src = [Link];
[Link]("title").textContent = [Link];
[Link]("rating").textContent = [Link];
[Link]("reviews").innerHTML = `
${[Link]('en-in')} ratings & ${[Link]('en-in')}
reviews`;
[Link]("price").innerHTML = [Link]('en-in',
{style:'currency', currency:'INR', minimumFractionDigits:0, maximumFractionDigits:0});
[Link](function(offer){
var li = [Link]("li");
[Link]("offers").appendChild(li);
})
</script>
</head>
<div class="row">
<div class="col-3">
</div>
<div class="col-9">
</span>
</div>
<div class="mt-3">
</div>
<div class="mt-2">
<h5>Available Offers</h5>
</ul>
</div>
</div>
</div>
</body>
</html>
Page -16
JavaScript Ajax
- XMLHttpRequest
Syntax:
fetch(“url”)
.then(function(response){
})
.then(function(data){
})
.catch(function(error){
// report error
})
.finally(function(){
})
Ex:
Data/[Link]
{
"title": "Apple iPhone 16 (Pink, 256 GB)",
"price": 79000,
"image": "../public/images/[Link]",
"offers": [
"Bank Offer5% cashback on Flipkart SBI Credit Card upto ₹4,000 per calendar quarterT&C",
"Bank Offer5% cashback on Flipkart Axis Bank Credit Card upto ₹4,000 per statement quarterT&C",
"Bank OfferUp To ₹50 Cashback on BHIM Payments App. Min Order Value ₹199. Offer Valid Once Per
User"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
function bodyload(){
fetch('../data/[Link]')
.then(function(response){
return [Link]();
})
.then(function(product){
[Link]("imgProduct").src = [Link];
[Link]("title").textContent = [Link];
[Link]("rating").textContent = [Link];
[Link]("reviews").innerHTML = `
${[Link]('en-in')} ratings & ${[Link]('en-in')}
reviews`;
[Link]("price").innerHTML = [Link]('en-in',
{style:'currency', currency:'INR', minimumFractionDigits:0, maximumFractionDigits:0});
[Link](function(offer){
var li = [Link]("li");
[Link]("offers").appendChild(li);
})
})
.catch(function(error){
[Link](error);
})
.finally(function(){
})
</script>
</head>
<div class="row">
<div class="col-3">
</div>
<div class="col-9">
<div class="mt-2">
</span>
<span id="reviews" class="fw-bold text-secondary mx-2"></span>
</div>
<div class="mt-3">
</div>
<div class="mt-2">
<h5>Available Offers</h5>
</ul>
</div>
</div>
</div>
</body>
</html>
[] Array
{} Object
Ex:
1. Data/[Link]
[
"price": 79000,
"image": "../public/images/[Link]",
"features": [
"256 GB ROM",
"1 year warranty for phone and 1 year warranty for in Box Accessories"
},
"price": 69000,
"image": "../public/images/[Link]",
"features": [
"126 GB ROM",
"1 year warranty for phone and 1 year warranty for in Box Accessories."
2. [Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function bodyload(){
fetch('../data/[Link]')
.then(function(response){
return [Link]();
})
.then(function(products){
[Link](function(product){
var tr = [Link]("tr");
[Link] = [Link];
var ul = [Link]("ul");
[Link](function(feature){
var li = [Link]("li");
[Link] = "10px";
[Link] = feature;
[Link](li);
})
[Link](ul);
[Link](tdTitle);
[Link](tdImage);
[Link](tdFeatures);
[Link](tdPrice);
[Link](tdRatings);
[Link]("tbody").appendChild(tr);
})
})
</script>
</head>
<h3>Products Table</h3>
<tr>
<th>Title</th>
<th>Preview</th>
<th width="300">Features</th>
<th>Price</th>
<th>Ratings</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
Weather API
[Link]
1318ca6725c69160d346c41fc0612596
4. Go to API Menu in Nav => Select Current Weather Data => API DOC => By City Name
[Link]
q=Hyderabad&appid=1318ca6725c69160d346c41fc0612596
[Link]
q=Hyderabad&appid=1318ca6725c69160d346c41fc0612596&units=metric
Ex:
1. Src/scripts/[Link]
function SearchClick(){
cityName = [Link]("txtCity").value;
fetch(api_url)
.then(function(response){
return [Link]();
})
.then(function(weatherObj){
[Link]("lblCity").innerHTML = cityName;
[Link]("lblTemp").innerHTML = `${[Link]}°C`;
})
2. [Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="../src/scripts/[Link]"></script>
</head>
<div class="input-group">
</div>
<div class="mt-2">
<span id="lblCity" class="fs-5 fw-bold"></span>
</div>
<div class="mt-3">
</div>
</div>
</body>
</html>
Page -17
Fakestore API
Weather API
- fetch()
- XMLHttpRequest
{} Object
[] Array
[ { }, { } ] Array of objects
Fakestore API
([Link]
URL: [Link]
Data
id : number,
title: string,
price: number,
description: string,
image:string,
category:string,
rating: {rate: number, count: number}
Ex:
1. Src/scripts/[Link]
function LoadCategories(){
fetch(`[Link]
.then(function(response){
return [Link]();
})
.then(function(categories){
[Link]("all");
[Link](function(category){
[Link] = [Link]();
[Link] = category;
[Link]("lstCategories").appendChild(option);
})
})
}
function LoadProducts(url){
[Link]("main").innerHTML = "";
fetch(url)
.then(function(response){
return [Link]();
})
.then(function(products){
[Link](function(product){
[Link] = "200px";
[Link] = `
${[Link]}
</div>
<div class="card-body">
<dl>
<dt>Price</dt>
<dd>${[Link]}</dd>
<dt>Rating</dt>
</dl>
</div>
<div class="card-footer">
</div>
`;
[Link]("main").appendChild(div);
})
})
function bodyload(){
LoadCategories();
LoadProducts("[Link]
GetCartCount();
function CategoryChange(){
LoadProducts("[Link]
} else {
LoadProducts(`[Link]
function SearchClick(){
LoadProducts(`[Link]
function SearchKeyUp(){
if([Link](searchString)){
[Link] = "block";
} else {
[Link] = "none";
}
}
function GetCartCount(){
[Link]("lblCount").innerHTML = [Link];
function GetCartTotal(){
var total = 0;
total+=[Link];
function AddClick(id){
fetch(`[Link]
.then(function(response){
return [Link]();
})
.then(function(product){
[Link](product);
alert(`${[Link]}\nAdded to Cart`);
GetCartCount();
GetCartTotal();
})
function ShowCartClick(){
[Link]("tbody").innerHTML = "";
[Link](function(item){
var tr = [Link]("tr");
[Link] = [Link];
[Link] = [Link];
[Link](tdTitle);
[Link](tdImage);
[Link](tdPrice);
[Link]("tbody").appendChild(tr);
})
GetCartTotal();
2. Js-examples/[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="../node_modules/bootstrap/dist/js/[Link]"></script>
<script src="../src/scripts/[Link]"></script>
</head>
<div>
</div>
</div>
<div>
</button>
<div class="offcanvas-header">
</div>
<div class="offcanvas-body">
<thead>
<tr>
<th>Title</th>
<th>Preview</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
</tfoot>
</table>
</div>
</div>
</div>
</header>
<section class="row">
<nav class="col-2">
<div class="my-3">
<div>
<select onchange="CategoryChange()" id="lstCategories" class="form-select">
</select>
</div>
</div>
</nav>
</main>
</section>
</body>
</html>
Page -18
- Array
- Object
- It is slow in interactions.
Map Type
Syntax:
[Link](key, value)
[Link](key)
[Link](key)
[Link]()
[Link]
[Link]()
[Link]()
[Link]()
[Link]()
Ex:
<script>
[Link](1, "TV");
[Link](1);
[Link](item + "<br>");
</script>
Date Type
Syntax:
- Javascript provides various date and time methods to get and set date.
getHours() 0 to 23
getMinutes() 0 to 59
getSeconds() 0 to 59
getMilliSeconds() 0 to 999
getDay() 0 to 6 [0 = Sunday]
getMonth() 0 to 11 [0 = January]
getFullYear() 2025
toDateString()
toLocaleDateString()
toTimeString()
toLocaleTimeString() etc..
Note: You have to depend of 3rd party date libraries to display and manipulate dates.
Ex:
<script>
var months = ["January", "Feb", "March", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov",
"December"];
[Link](`${[Link]()} ${weekdays[[Link]()]},
${months[[Link]()]} ${[Link]()}`);
</script>
setHours()
setMinutes()
setSeconds()
setMilliSeconds()
setDate()
setMonth()
setFullYear()
Syntax:
[Link](15);
[Link](29);
Ex:
<script>
[Link](15);
} else {
[Link]("Good Evening");
</script>
Timer Events:
setTimeout()
clearTimeout()
setInterval()
clearInterval()
setTimeout()
- It loads task into memory and keeps it inactive for specific duration of time.
Syntax:
setTimeout(function(){ }, interval);
clearTimeout()
Syntax:
clearTimeout(thread);
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function Level1(){
function Level2(){
function Level3(){
function VolumeIncrease(){
l1 = setTimeout(Level1, 4000);
l2 = setTimeout(Level2, 8000);
l3 = setTimeout(Level3, 15000);
function CancelClick(){
clearTimeout(l2);
</script>
</head>
<body>
<p></p>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function Clock(){
[Link]("h1").innerHTML = time;
function bodyload(){
setInterval(Clock,1000);
</script>
</head>
<body onload="bodyload()">
<h1 align="center"></h1>
</body>
</html>
Page-19
Operators
Debounce
- setTimeout()
- clearTimeout()
Throttle
Syntax:
setInterval(function(){}, interval);
clearInterval(reference_name);
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function Clock(){
var now = new Date();
[Link]("h1").innerHTML = time;
function bodyload(){
setInterval(Clock,1000);
</script>
</head>
<body onload="bodyload()">
<h1 align="center"></h1>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.container {
width: 600px;
display: grid;
padding: 20px;
font-size: 50px;
font-family: Arial;
font-weight: bold;
text-align: center;
height: 70px;
button {
font-size: 20px;
padding: 10px;
background-color: lightblue;
border: none;
</style>
<script>
var ms = 0;
var sec = 0;
function StartClock(){
var hours = 0;
var min = 0;
ms++;
if(ms==999){
ms = 0;
sec++;
if(sec==59){
min++;
[Link]("ms").innerHTML = ms;
[Link]("sec").innerHTML = sec;
[Link]("min").innerHTML = min;
var thread;
function StartClick(){
thread = setInterval(StartClock,1);
}
function StopClick(){
clearInterval(thread);
</script>
</head>
<body>
<div class="container">
<div>
<span id="hours">00</span>
</div>
<div>
<span id="min">00</span>
</div>
<div>
<span id="sec">00</span>
</div>
<div>
<span id="ms">000</span>
</div>
</div>
<br><br>
<button onclick="StartClick()">Start</button>
<button onclick="StopClick()">Stop</button>
</body>
</html>
- Number
- String
- Boolean
- Null
- Undefined
- Symbol
- Bigint
- Array
- Object
- Map
- Date
- Regular Expression / /
Note: Primitive types use value and Non Primitive types use reference.
Ex:
<script>
var a = 10;
b = 20;
[Link](`a=` + a + "<br>");
[Link] = 'John';
</script>
Javascript Operators
a +b
a, b => operands
+ => entity
- Based on number of operands an operator can handle, they are categorized into
a) Unary Operator
b) Binary Operator
c) Ternary Operator
++ increment
-- decrement
! not
Increment
var x = 10;
var y = x++; x=11, y=10
var x = 10;
Decrement
var x = 10;
var x = 10;
1. Src/[Link]
function LoadProduct(id){
[Link]("txtRange").value=id;
fetch(`[Link]
.then(function(response){
return [Link]();
})
.then(function(product){
[Link]("lblTitle").innerHTML = [Link];
[Link]("imgProduct").src = [Link];
[Link]("lblPrice").innerHTML = [Link]('en-us',
{style:'currency', currency:'USD'});
})
let productId = 1;
function NextClick(){
productId++;
LoadProduct(productId);
}
function PreviousClick(){
productId--;
LoadProduct(productId);
function SliderChange(){
productId = sliderValue;
LoadProduct(productId);
function LoadProductAuto(){
productId++;
[Link]("txtRange").value=productId;
fetch(`[Link]
.then(function(response){
return [Link]();
})
.then(function(product){
[Link]("lblTitle").innerHTML = [Link];
[Link]("imgProduct").src = [Link];
[Link]("lblPrice").innerHTML = [Link]('en-us',
{style:'currency', currency:'USD'});
})
var thread;
function PlayClick(){
function PauseClick(){
clearInterval(thread);
2. Js-examples/[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/[Link]">
<script src="../src/scripts/[Link]"></script>
</head>
<div id="lblTitle"></div>
</div>
</div>
<div id="lblPrice" class="position-absolute p-3 fs-5 top-0 end-0 badge rounded rounded-circle
bg-danger text-white"></div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
[ + , / , * ] etc.
?:
Syntax:
if (condition)
{
true;
else
false;
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function ButtonClick(){
[Link]("button").textContent =
([Link]("button").textContent=="Start")?"Stop":"Start";
function SortClick(){
</script>
</head>
<body>
<button onclick="ButtonClick()">Start</button>
</body>
</html>
Page-20
Operators continue
JavaScript Operators
1. Unary
2. Binary
3. Ternary
4. Arithmetic Operators
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus Division
++ Increment
-- Decrement
Ex:
1. Src/[Link]
function AmountChange(){
[Link]("txtAmount").value =
[Link]("rangeAmount").value;
function YearChange(){
[Link]("txtYears").value =
[Link]("rangeYears").value;
function RateChange(){
[Link]("txtRate").value =
[Link]("rangeRate").value;
function CalculateClick(){
var P = parseInt([Link]("txtAmount").value);
var r = parseFloat([Link]("txtRate").value)/12/100;
var n = parseInt([Link]("txtYears").value)*12;
2. [Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/[Link]">
<script src="../src/scripts/[Link]"></script>
</head>
<div>
<div>
</div>
<div>
</div>
</div>
<div class="my-2">
<div>
<span>₹ 1,00,000/-</span>
</div>
</div>
</div>
<div class="mt-3">
<div>
</div>
<div>
</div>
</div>
<div class="my-2">
<div>
<span>1 Year</span>
</div>
</div>
</div>
<div class="mt-3">
<div>
</div>
<div>
</div>
</div>
<div class="my-2">
<div>
<span>10%</span>
<span class="float-end">24%</span>
</div>
</div>
</div>
<div class="text-center">
</div>
</div>
</div>
<div class="mt-4">
</div>
</div>
</div>
</body>
</html>
5. Comparison Operators
== Equal
!= Not Equal
“10” == 10 // true
6. Logical Operators
&& AND
|| OR
! Not
expression-1 && expression-2 => returns true only when both expressions are true
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
var user = {
user_name: "john_nit",
password: "john@123",
email: "john@[Link]"
function LoginClick(){
[Link]("Login Success..");
} else {
alert("Invalid Credentials");
</script>
</head>
<body>
<dl>
<dt>Password</dt>
</dl>
<button onclick="LoginClick()">Login</button>
</body>
</html>
7. Assignment Operators
+= Add and assign
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function SubmitClick(){
if([Link]){
}
[Link]("p").innerHTML = courseName;
</script>
</head>
<body>
<ul>
</ul>
<button onclick="SubmitClick()">Submit</button>
<h3>Selected Courses</h3>
<p></p>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
var position = 1;
function MoveRight(){
position *= 2;
function MoveLeft(){
position /= 2;
</script>
</head>
<body>
<br><br>
</html>
Task:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
var data = [
</script>
</head>
<body>
<ul>
<button>Submit</button>
<p>Course Names</p>
<p>Total Amount</p>
</body>
</html>
Page-21
Statements
Syntax:
2. new
3. delete
Syntax:
delete [Link];
4. in
Syntax:
5. typeof
var x = “John”;
typeof x ; // string
6. instanceOf
Syntax:
7. void
Syntax:
8. yield
Syntax:
yield value;
Javascript Statements
1. Selection Statements
2. Looping Statements
3. Iteration Statements
for..in, for..of
4. Jump Statements
IF Selector:
a) Forward Jump
b) Simple Decision
c) Multilevel Decisions
d) Multiple Choices
Forward Jump
- It is a decision making approach where statements are executed only when condition
evaluates to true.
Syntax:
if (booleanExpression | value )
{
statements;
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
var user = {
Card: "4444555566667890",
Cvv: "2345",
Expiry: "2026"
function VerifyCard(){
if(card===[Link]){
[Link]("txtCvv").disabled = false;
}
}
</script>
</head>
<body>
<h3>Payment Details</h3>
<dl>
<dt>Your Card</dt>
<dt>Cvv</dt>
<dt>Expiry</dt>
<dd>
<option>Select Expiry</option>
<option>2024</option>
<option>2025</option>
<option>2026</option>
</select>
</dd>
</dl>
<button disabled>Pay</button>
</body>
</html>
Simple Decision:
Syntax:
if (condition )
statement on true;
else
statement on false;
- If there are multiple conditions and every condition must be satisfied, then
better to use multilevel approach.
- It uses forward only technique with individual alternative for every condition.
Syntax:
if (condition1)
if(condition2)
else
else
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
var user = {
user_name: "john_nit",
password: "john@123",
function LoginClick(){
if([Link]===0){
} else {
if(user.user_name===username){
if([Link]===password){
[Link]("Success..");
} else {
alert("Invalid Password");
}
} else {
</script>
</head>
<body>
<dl>
<dt>User Name</dt>
<dt>Password</dt>
</dl>
<button onclick="LoginClick()">Login</button>
</body>
</html>
Multiple Choices:
Syntax:
if(condition1)
// statements on condition-1
else if(condition2)
// statements on condition-2
else
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/[Link]">
<script>
var user = {
mobile: "+919876543211",
email: "john@[Link]",
password: "john11"
function ToggleContainers(){
[Link]("loginContainer").[Link] = "none";
[Link]("pwdContainer").[Link] = "block";
function ContinueClick(){
if(userid===[Link]){
ToggleContainers();
} else if(userid===[Link]){
ToggleContainers();
} else {
function LoginClick(){
if(password===[Link]){
[Link](`<h1>${flag}</h1>`);
} else {
</script>
</head>
<div class="mt-4">
<div id="loginContainer">
<div>
</div>
<div>
</div>
</div>
</div>
</body>
</html>
Page-22
Switch Selector
Selection Statements
- If statements
a) Forward Jump
b) Simple Decision
c) Multilevel
d) Multiple Choices
Ans: If multiple conditions are configured then it verifies all conditions until it matches
the required. It will increase the compiling and processing time. It is slow.
Switch Statement
Syntax:
switch(value | expression)
statements;
jump;
default:
statements;
jump;
Debug Process:
- Go to “Sources” category
Ex:
<script>
switch(n)
case 1:
[Link]("One");
break;
case 2:
[Link]("Two");
break;
case 3:
[Link]("Three");
break;
case 4:
[Link]("Four");
break;
default:
break;
</script>
FAQ’s:
A. Yes
A. “break" will exit the block but it is continued with compiling the script.
“return” will exit the block and terminates the compiling. It can be used in a function.
A. Yes. Break is not mandatory. If not defined then it stops at the end of switch.
case 1:
case 2:
statements;
jump;
Ex:
<script>
switch([Link]())
case "red":
case "green":
case "blue":
break;
case "lines":
case "dots":
case "strips":
break;
default:
break;
</script>
Ex:
<script>
switch(choice)
case "y":
case "Y":
break;
case "n":
case "N":
break;
default:
break;
</script>
Syntax:
switch(true)
case condition:
statements;
jump;
Ex:
<script>
switch(true)
break;
break;
}
</script>
Programs:
function FindGreatest(a, b)
// logic
function FindGreatest(a, b, c)
}
O/P:
FindGreatest(20,10, 30)
Ex:
<script>
function FindGreatest(a,b,c){
else if(b>c){
} else {
[Link]("<br>");
</script>
Page-23
Loops
Syntax:
var i=1
i<condition
- Counter specifies how to proceed, you can increment, decrement, step etc
Ex:
<script>
[Link](data[i] + "<br>");
</script>
Ex:
<script>
function PrintTable(n){ // 5
PrintTable(parseInt(prompt("Enter Number")));
</script>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function bodyload(){
var data = [
];
[Link](function(item){
var li = [Link]("li");
[Link] = [Link];
var ul = [Link]("ul");
[Link](function(product){
ul_li.innerHTML = product;
[Link](ul_li);
[Link](ul);
[Link]("ol").appendChild(li);
})
})
</script>
</head>
<body onload="bodyload()">
<ol>
</ol>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function bodyload(){
var data = [
];
var li = [Link]("li");
[Link] = data[i].Category;
var ul = [Link]("ul");
ul_li.innerHTML = data[i].Products[j];
[Link](ul_li);
[Link](ul);
[Link]("ol").appendChild(li);
}
</script>
</head>
<body onload="bodyload()">
<ol>
</ol>
</body>
</html>
Ex:
<script>
function PrintTriangle(n)
for(i=1;i<=n; i++)
[Link]("* ");
[Link]("<br>");
PrintTriangle(parseInt(prompt("Enter Number")));
</script>
Ex:
<script>
function PrintTriangle(n)
for(i=n;i>=1; i--)
[Link]("* ");
[Link]("<br>");
PrintTriangle(parseInt(prompt("Enter Number")));
</script>
2. While Loop
while(condition)
counter;
statements;
Ex:
<script>
var i = 1;
while(i<=10)
[Link](i + "<br>");
i++;
</script>
3. Do while
- It is similar to while but ensures that statements will execute at least once even when condition
evaluates to false.
Syntax:
do {
statements;
counter;
} while (condition);
<script>
var i = 1;
do {
[Link](i + "<br>");
i++;
} while(i<=10);
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function DisablePin(){
[Link]("pin").disabled = false;
function VerifyClick(){
if(pin==="4567"){
[Link]("Success..");
}else{
[Link]("pin").disabled = true;
setTimeout(DisablePin,10000);
</script>
</head>
<body>
Your PIN :
<button onclick="VerifyClick()">Verify</button>
<p></p>
</body>
</html>
Page-24
Functions
Jump Statements
a) break
b) return
c) continue
Ex:
Data/[Link]
"user_id": "john"
},
"user_id": "john12"
},
"user_id": "john_nit"
},
"user_id": "david"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function VerifyUser(){
fetch('../data/[Link]')
.then(function(response){
return [Link]();
})
.then(function(users){
if(user.user_id===userid){
break;
} else {
})
</script>
</head>
<body>
<h3>Register</h3>
<dl>
<dt>User Id</dt>
<dd id="lblMsg"></dd>
</dl>
</body>
</html>
Ex:
<script>
if(i===5 || i===8)
continue;
[Link](i + "<br>");
}
</script>
Ex:
<script>
fetch('[Link]
.then(function(response){
return [Link]();
})
.then(function(products){
if([Link]==="jewelery" || [Link]==="electronics") {
continue;
[Link](`${[Link]} - <b>${[Link]}</b><br>`);
})
</script>
b) Run Time
- Compile time errors are syntactical errors due to which a program fails to
run.
- Run time errors occur while using application. Compiler can’t understand
Syntax:
try
//statements to execute;
if(condition) {
catch(error) {
// report error
finally
// execute always
Ex:
<script>
try {
if(b===0){
if(b>a){
var c = a / b;
[Link](`Division=${c}<br>`);
catch(error)
{
[Link](error + "<br>")
finally {
[Link]("Program End");
</script>
Summary
- Selection Statements
- Jump Statements
Javascript Functions
a code block with reference name. So that you can reuse the code without
rewriting.
a) reusability
b) extensibility
c) maintainability
d) testability etc.
Configuring Function
a) Declaration
b) Expression
Syntax: Declaration
function Name()
Syntax: Expression
- Declaration allows hoisting of function, you can declare at any location and
access from any another location. It doesn’t require any order of accessibility.
- Expression will not allow hoisting even when configured with “var” keyword.
Ex:
<script>
var result;
if(password==="admin"){
result = function(){
[Link]("Success..");
} else {
result = function(){
[Link]("Invalid Password");
result();
</script>
- Every function declaration have 3 parts
a) Declaration
b) Signature
c) Definition
{} => Definition
Function Parameters
Syntax:
function Name(param)
{
}
Name(value);
param = value;
Ex:
<script>
function PrintNumbers(howMany){
[Link](i + "<br>");
PrintNumbers(5);
PrintNumbers(10);
</script>
Page-25
Function Params and Return
- Function Declaration
- Function Expression
- Function Definition
- Function Parameters
a) Formal Parameter
b) Actual Parameter
value.
params = value
- Parameter can handle any type of data
a) Primitive
b) Non Primitive
c) Function
Ex:
<script>
function Demo(data)
[Link](function(item){
[Link]([Link] + "<br>");
})
Demo([{Name:'TV'}, {Name:'Mobile'}]);
</script>
Ex:
<script>
function Demo(action)
action();
Demo(function(){
})
</script>
- If you want to skip any parameter then it requires to configure with “undefined”.
Ex:
<script>
if(name){
[Link](`Id=${id}<br>Name=${name}<br>Price=${price}`);
} else {
[Link](`Id=${id}<br>Price=${price}`);
}
}
</script>
Syntax:
function Name(params=value)
Name(undefined)
Ex:
<script>
if(name){
[Link](`Id=${id}<br>Name=${name}<br>Price=${price}`);
} else {
[Link](`Id=${id}<br>Price=${price}`);
}
</script>
- A function can have max 65535 params on a 64bit memory device. - Too many parameters will
cause Injection Attacks.
Syntax:
function Name(…params)
- You can use rest parameter with other parameters, but it must be last in formal list.
<script>
[Link](`<h1>${title}</h1>Id=${id}<br>Name=${name}<br>Price=${price}`);
</script>
- Function supports spread operator to spread values of one argument into multiple
parameters.
Ex:
<script>
[Link](`Id=${id}<br>Name=${name}<br>Price=${price}`);
Product(...data);
</script>
FAQ: What is difference between rest and spread?
Rest : Formal
Spread : Actual
- It keeps the memory of a function alive even after it completes the actions defined.
Syntax:
function Name()
return value;
Name() = value;
Ex:
<script>
function Addition(a, b)
return a + b;
function Result(){
[Link](`Addition=${Addition(40,20)}`);
Result();
</script>
a) Primitive
b) Non Primitive
c) Function
“Function Currying”.
Syntax:
function Name()
{
return function() { }
Name()();
Ex:
<script>
function Demo(){
return function(){
return function(){
[Link]("Function Currying");
Demo()()();
</script>
- If a function returns different value even when the function actions and parameters are
Ex:
<script>
var count = 1;
function Demo(n){
return count+=n;
[Link](Demo(5) + "<br>");
[Link](Demo(5) + "<br>");
[Link](Demo(5) + "<br>");
</script>
- If a function returns the same value even when it is configured with different parameters
Ex:
<script>
function Demo(n){
n = 10;
return n;
[Link](Demo(5) + "<br>");
[Link](Demo(10) + "<br>");
[Link](Demo(15) + "<br>");
</script>
- A function can be configured with multiple return, which is used to return different values
based on a condition.
Syntax:
function Name()
if(condition)
return A;
else {
return B;
Ex:
<script>
function Demo(n){
if(isNaN(n)){
return [Link]();
} else {
return ++n;
[Link](Demo(prompt("Enter Value")));
</script>
Page-26
Functions continued
Function Parameters
Function Return
Higher Order
Function Currying
Function Closure
inner function, but inner function members are not accessible to outer.
Ex:
<script>
function Outer(){
var x = 10;
function Inner(){
var y = 20;
return x + y;
[Link]("Addition=" + Inner());
Outer();
</script>
Function Chaining
Syntax:
function Name()
{
return {
f1() {
return this;
},
f2() {
return this;
Name().f1().f2()
Name().f2().f1()
Name().f2()
Ex:
<script>
function Demo()
return {
A(){
[Link]("A");
return this;
},
B(){
[Link]("B");
return this;
},
C(){
[Link]("C");
return this;
Demo().A().C();
Demo().C().B();
Demo().A();
Demo().A().C().B();
</script>
Function Recursion
function f1()
f1();
f1();
Ex:
<script>
function f1()
[Link]("Hello !");
setTimeout(f1,3000);
f1();
</script>
Ex:
<script>
function Factorial(n){
if(n===1){
return 1;
} else {
return n * Factorial(n-1);
[Link](`Factorial of 6 is ${Factorial(6)}`);
</script>
Anonymous Function
Syntax:
(function(){ })();
Ex:
<script>
(function(){
[Link]("Anonymous");
})(); // IIFE
</script>
Function Promise
a) Resolve
b) Reject
- Resolve is on success.
- Reject is on failure.
Syntax:
if(condition) {
resolve();
} else {
reject();
})
demo().then().catch().finally()
Ex:
<script>
if(url==="[Link]"){
resolve([{Name:'TV'}, {Name:'Mobile'}]);
} else {
})
[Link](function(response){
[Link](response);
})
.catch(function(error){
[Link](error);
})
.finally(function(){
[Link]("Request End");
})
</script>
Async Functions
Syntax:
Name().then().catch().finally()
Ex:
<script>
GetData().then(function(response){
[Link](response);
})
.catch(function(error){
[Link](error);
})
.finally(function(){
[Link]('End');
})
</script>
Function Generator
in sequential order.
- It implicitly yields value and moves to next.
Syntax:
function* Generator()
Ex:
<script>
function* GetData(){
yield 10;
yield "A";
[Link]([Link]())
[Link]([Link]())
[Link]([Link]())
[Link]([Link]())
</script>
Page -27
Events
Sudhakar Sharma (Sudhakar Sharma Naresh IT)•7 Jan
Arrow Functions
- You can minify the code. Minification reduces the file size.
Syntax:
return a + b;
Syntax:
[Link](“statement-1”);
[Link](“statement-2”);
// statements
Syntax:
[Link](item=> {
[Link](item);
})
Ex:
<script>
fetch('[Link]
.then(response=>[Link]())
.then(products=> {
[Link]((product,index)=> {
[Link](`[${index}]${[Link]}<br>`);
})
})
</script>
Javascript Events
Event Handler
on : is a handler name
<button onclick=“f1()”>
Event Listener
“addEventListener()”
Syntax:
[Link](“button”).addEventListener(“event”, ()=> {
})
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function bodyload(){
[Link] = "Insert";
[Link]("click",()=>{
[Link]("Record Inserted");
})
[Link]("body").appendChild(button);
[Link]("btnDelete").addEventListener("click",function(){
[Link]("Record Deleted");
})
</script>
</head>
<body onload="bodyload()">
<button id="btnDelete">Delete</button>
</body>
</html>
Event Arguments
a) this
b) event
includes id, name, value, className, width, height, src, href etc.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
switch([Link]){
case "Insert":
[Link]("Record Inserted");
break;
case "Delete":
[Link]("Record Deleted");
break;
case "Update":
[Link]("Record Updated");
}
</script>
</head>
<body>
</body>
</html>
- You can use both spread and rest approach to handle parameters.
Syntax:
function Details(…params) { }
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function DetailsClick(element,...product){
[Link](`Id=${id}<br>Name=${name}<br>Stock=${stock}<br>Cities=${citites}`);
</script>
</head>
<body>
</body>
</html>
Note: Event listener can have only one argument, which is an event
details.
Syntax:
.addEventListener(function(event){
})
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function bodyload(){
[Link]("btnInsert").addEventListener("click",(e)=>{
})
}
</script>
</head>
<body onload="bodyload()">
</body>
</html>
Syntax:
function ChildEvent(e)
[Link]();
<button onclick=“ChildEvent(event)”>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function NavClick(){
alert("Navbar Clicked");
function SearchClick(e){
[Link]();
alert("Search Clicked");
</script>
</head>
<body>
<h3>Navbar</h3>
<button onclick="SearchClick(event)">Search</button>
</nav>
</body>
</html>
- They have default events that fire-up along with custom events.
Syntax:
function Submit(e)
[Link]();
<form onsubmit=“Submit(event)”>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function FormSubmit(e){
[Link]();
</script>
</head>
<body>
<form onsubmit="FormSubmit(event)">
User name :
<button type="submit">Submit</button>
</form>
</body>
</html>
Page-28
Events Examples
1. What is Event
2. Event Handler
3. Event Listener
4. Events Args
5. Propagation
6. Prevent Default
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function StartClick(){
setTimeout(()=>{
[Link]("Macro Task");
},0);
resolve("Microtask");
});
[Link](response=>{
[Link](response);
})
[Link]("Normal Task");
</script>
</head>
<body>
<button onclick="StartClick()">Start</button>
</body>
</html>
What is Event Profiling?
- You can go to browser debugger and select performance to track the events.
Browser Events
- Browser window object provides various events that you can use for elements in page.
1. Mouse Events
2. Keyboard Events
3. Button Events
4. Clipboard Events
Mouse Events:
onmouseover
onmouseout
onmousedown
onmouseup
onmousemove
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
nav img {
padding: 5px;
nav img:hover {
cursor: grab;
</style>
<script>
function bodyload(){
fetch("../data/[Link]")
.then(res=>[Link]())
.then(mobiles=>{
[Link](mobile=>{
[Link] = [Link];
[Link]="100";
[Link]="100";
[Link]="my-2";
[Link]("mouseover",()=>{
[Link]("imgMobile").src = [Link];
})
[Link]("nav").appendChild(img);
})
})
</script>
</head>
<div class="col-2">
<nav></nav>
</div>
<div class="col-10">
</div>
</div>
</body>
</html>
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function Animate(e){
[Link] = "fixed";
}
</script>
</head>
<body onmousemove="Animate(event)">
</body>
</html>
Keyboard Events
onkeyup
onkeydown
onkeypress
onfocus
onblur
onchange
Clipboard Events
oncut
oncopy
onpaste
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<dl>
</dl>
</body>
</html>
Button Events
onclick
ondblclick
onselectstart
Note: You can disable any event with function that return false.
Syntax:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
[Link] = function(){
return false;
}
[Link] = function(){
return false;
</script>
</head>
<body>
</body>
</html>
Page-29
State Management
across requests.
a) Client Side
b) Server Side
a) Query String
b) Session Storage
c) Local Storage
d) Cookies
Query String
Ex:
state/[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="./[Link]">
<dl>
<dt>User Name</dt>
</dl>
<button>Login</button>
</form>
</body>
</html>
State/[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function bodyload(){
function Signout(){
[Link] = "./[Link]";
</script>
</head>
<body onload="bodyload()">
<h2>Dashboard</h2>
<span id="lblUser"></span>
<button onclick="Signout()">Signout</button>
</div>
</body>
</html>
Session Storage
- It is a browser storage.
- It is temporary storage.
Syntax:
[Link](key, value)
.getItem(key)
.removeItem(key)
.clear()
Ex:
state/[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function LoginClick(){
[Link]("uname", username);
[Link] = "./[Link]";
</script>
</head>
<body>
<dl>
<dt>User Name</dt>
<button onclick="LoginClick()">Login</button>
</body>
</html>
state/[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function bodyload(){
if(uname===null){
[Link] = "./[Link]";
} else {
}
}
function Signout(){
[Link]("uname");
[Link] = "./[Link]";
</script>
</head>
<body onload="bodyload()">
<h2>Dashboard</h2>
<span id="lblUser"></span>
<button onclick="Signout()">Signout</button>
</div>
</body>
</html>
Local Storage
[Link](key,value)
.getItem(key)
.removeItem(key)
.clear()
Ex:
state/[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function LoginClick(){
[Link]("uname", username);
[Link] = "./[Link]";
</script>
</head>
<body>
<dl>
<dt>User Name</dt>
</dl>
<button onclick="LoginClick()">Login</button>
</body>
</html>
state/[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function bodyload(){
if(uname===null){
[Link] = "./[Link]";
} else {
function Signout(){
[Link]("uname");
[Link] = "./[Link]";
</script>
</head>
<body onload="bodyload()">
<h2>Dashboard</h2>
<span id="lblUser"></span>
<button onclick="Signout()">Signout</button>
</div>
</body>
</html>
Cookies
Syntax:
- To remove cookie you have to set cookie empty with expiry date as
Ex:
state/[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function LoginClick(){
[Link] = "./[Link]";
</script>
</head>
<body>
<dl>
<dt>User Name</dt>
</dl>
<button onclick="LoginClick()">Login</button>
</body>
</html>
state/[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function bodyload(){
if(uname===null){
[Link] = "./[Link]";
} else {
function Signout(){
[Link] = `uname=''; expires=${new Date("2026-01-08")}`;
[Link] = "./[Link]";
</script>
</head>
<body onload="bodyload()">
<h2>Dashboard</h2>
<span id="lblUser"></span>
<button onclick="Signout()">Signout</button>
</div>
</body>
</html>
- Libraries use legacy system which loads every component but uses only few.
It is heavy on applicaton.
d) ESModule
“module”.
<script type=“module”>
</script>
a) variables
b) functions
c) classes etc.
- You can import and use the module members from any page.
Ex:
[Link]
function Hello(){
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="module">
[Link]("h1").innerHTML = title;
</script>
</head>
<body>
<h1></h1>
<p></p>
</body>
</html>
Page-30
-Default Export
-Import
Syntax:
- You can import all members from a module using “*” meta character and
set alias.
Syntax:
[Link]
Ex:
[Link]
return a + b;
return a - b;
return a - b;
[Link]
[Link]
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="module">
[Link]("h1").innerHTML = AdminTitle();
[Link]("p").innerHTML= UserTitle();
[Link]("div").innerHTML = `Add=${[Link](20,30)}`;
</script>
</head>
<body>
<h1></h1>
<p></p>
<div></div>
</body>
</html>
- It provides pre-defined data and logic which you customize and implement
according to requirements.
Configuring Class
1. Declaration
class Name
2. Expression
Class Members
1. Property
2. Accessor
3. Method
4. Constructor
Property
- It is mutable.
Syntax:
class Product
{
Name = “TV”;
Price = 34000;
Stock = true;
Cities = [ ];
Rating = { };
- You can access class members by using instance of class, if they are
non-static.
Syntax:
class Product
_Name = value;
#Price = value;
}
- JavaScript ES7+ versions support static members.
Static
- Memory allocated for first object will continue for other objects.
- Static members are accessible inside or outside class by using class name.
Non Static
Syntax:
class Demo
static s = 0; // continuous
n = 0; // discrete
}
Ex:
<script>
class Demo
static s = 0;
n = 0;
Print(){
Demo.s = Demo.s + 1;
this.n = this.n + 1;
[Link](`s=${Demo.s} n=${this.n}<br>`);
[Link]();
[Link]();
[Link]();
</script>
Accessors
- You can manage read and write operations on property using accessors.
a) get() Getter
b) set() Setter
Syntax:
get aliasName()
return property;
set aliasName(newValue)
property = newValue;
Ex:
<script>
class Product
_productName;
get ProductName(){
return this._productName;
set ProductName(newName){
if(role==="admin"){
this._productName = newName;
} else {
[Link] = productname;
if([Link])
{
[Link](`Product Name = ${[Link]}`);
</script>
Method
Syntax:
class Name
Method(params)
Constructor
- A constructor is used for instantiation.
Syntax:
class Name
constructor(){ }
Ex:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
class Database
constructor(dbName){
[Link](`Connected with ${dbName} database<br>`);
Insert(){
[Link](`Record Inserted..`);
Update(){
[Link](`Record Updated..`);
Delete(){
[Link](`Record Deleted..`);
function Action(command){
switch(command){
case "Insert":
[Link]();
break;
case "Update":
[Link]();
break;
case "Delete":
[Link]();
break;
</script>
</head>
<body>
<select>
<option>Select Database</option>
<option>Oracle</option>
<option>MySQL</option>
<option>MongoDB</option>
</select>
<button onclick="Action('Delete')">Delete</button>
<button onclick="Action('Insert')">Insert</button>
<button onclick="Action('Update')">Update</button>
</body>
</html>
THIS IS THE END