0% found this document useful (0 votes)
18 views

Unit III

The document discusses JavaScript including its introduction, data types, variables, operators, conditional statements, iteration, switch case, arrays, functions, objects, DOM, asynchronous programming and examples. It covers how JavaScript can make web pages dynamic and interactive, add interactivity to HTML pages, read and write HTML elements, and validate data. It also discusses the different ways JavaScript code can be run and placed in web pages.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Unit III

The document discusses JavaScript including its introduction, data types, variables, operators, conditional statements, iteration, switch case, arrays, functions, objects, DOM, asynchronous programming and examples. It covers how JavaScript can make web pages dynamic and interactive, add interactivity to HTML pages, read and write HTML elements, and validate data. It also discusses the different ways JavaScript code can be run and placed in web pages.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

UNIT III

CLIENT SIDE SCRIPTING: JAVA SCRIPT


Introduction to JavaScript -Data Types, Variables, Operators, Conditional Statement, Iteration,
Switch Case, Arrays, Dialog boxes- Functions: reduce, spread, rest – Event handling-Objects: Built-
in -Global object - DOM-Object Properties – Asynchronous Programming.
Illustrative programs: Mobile Number Validation, Rupee to Dollar & Dollar to Rupee
Conversion using DOM, RGB Range Selector.

3.1 INTRODUCTION TO JAVASCRIPT


• JavaScript was initially developed by Brendan Eich as part of the Netscape 2.0 release. The
language was called Live Script for a while in its early stages. But on December 4, 1995,
before the final release of Netscape 2.0, the language was publicly announced as
JavaScript.and has appeared in all Netscape and Microsoft browsers since 1996
• JavaScript became especially popular after the 1.1 release as part of Netscape’s 3.0 browser.
This version of JavaScript allowed web page developers to produce the familiar rollover
effect: as the mouse moves over images, the images change. Changing the style or even
the content of a document.
• Another flavour of JavaScript, known as ECMAScript. Soon after announcing JavaScript,
Sun and Netscape approached an organization then known as the European Computer
Manufacturers Association (ECMA) to produce a standard for JavaScript. JavaScript is an
implementation of the ECMAScript language standard.
• JavaScript is a Client side scripting Language designed to add interactivity to HTML pages.
• It enhances the functionality and appearance of web pages.
• JavaScript is an interpreted language. All major web browsers contain JavaScript interpreters,
which process the commands written in JavaScript.

1
JavaScript server two purposes
i) It introduces client-side scripting which makes web pages more dynamic and interactive
ii) It provides the programming foundation for the more complex server-side scripting.
Why JavaScript:
i) JavaScript can put dynamic text into an HTML page
ii) JavaScript can react to events - A JavaScript can be set to execute when something happens, like
when a page has finished loading or when a user clicks on an HTML element
iii)JavaScript can read and write HTML elements : A JavaScript can read and change the content
of an HTML element
iv) JavaScript can be used to validate data - A JavaScript can be used to validate form data before it
is submitted to a server. This saves the server from extra processing.
v) JavaScript is also used in many other areas such as server-side development, mobile app
development and so on.
vi) JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve
information on the visitor's computer.

We can run JavaScript in several ways:


• Using console tab of web browsers
• By creating web pages
Using console tab of web browsers
The console.log() method is used to write
messages to these consoles
let sum = 44;
console.log(sum); // 4
Syntax:
console.log(message);// message refers to either
a variable or a value.

Print a Sentence
console.log("I love JS");
output:
I love JS

2
Example 2: Print Values Stored in Variables
const greet = 'Hello';
const name = 'Jack';
console.log(greet + ' ' + name);
It is commonly used for testing/debugging code.
By creating web pages
• 3 Places to put JavaScript code
i) Between the body tag of html
ii) Between the head tag of html
iii)In .js file (external javaScript)
• Structure of JavaScript
<script type="text/javascript">
document.writeln(“Helo World!);
</script>
<script type=”text/javascript”> </script> tag is used to insert a JavaScript in the HTML document.
type attribute to define the scripting language.
i) Between the head tag of html
<html>
<head>
<script type="text/javascript">
document.writeln(“Helo World!);
</script>
</head>
<body>
----
</body>
</html>
• Between the body tag of html
It is possible to have script code inside the body tag also as shown below. If it is placed inside
the body tag, the script will be executed when the content of HTML document is displayed.
<html>
<body>
<script type="text/javascript">
3
............
</script>
</body>
</html>
• The document.write() command between the <script> and </script> tags is a standard
JavaScript command for writing output to a page.
• The browser will recognize statements inside the
<script=”type=”text/javascript”></script> as a
JavaScript command and execute the code line
<html>
<head>
<script type="text/javascript">
document.writeln( "<h1>Welcome to JavaScript Programming!</h1>" );
</script>
</head>
<body>
</body>
</html>

• Using an External JavaScript


• JavaScript can also be placed in external files. External JavaScript files often contains code to be
used on several different web pages.
• External JavaScript files have the file extension .js.
• External script cannot contain the <script></script> tags. To use an external script, point to the
.js file in the "src" attribute of the <script> tag:
ext.js
document.writeln( "<h1>Welcome to JavaScript Programming!</h1>" );
demo3.html
<html>
<head>
<script type="text/javascript" src="ext.js"></script>
</head>
<body>
</body>
</html>

4
Advantages of External JavaScript
• It helps in the reusability of code in more than one HTML file.
• It allows easy code readability.
• It is time-efficient as web browsers cache the external js files, which further reduces the page
loading time.
• It enables both web designers and coders to work with html and js files parallelly and separately,
i.e., without facing any code conflictions.
• The length of the code reduces as only we need to specify the location of the js file.

DisAdvantages of External JavaScript


• The stealer may download the coder's code using the url of the js file.
• If two js files are dependent on one another, then a failure in one file may affect the execution of
the other dependent file.
• The web browser needs to make an additional http request to get the js code.
• A tiny to a large change in the js code may cause unexpected results in all its dependent files.
• We need to check each file that depends on the commonly created external javascript file.
• If it is a few lines of code, then better to implement the
internal javascript code

• Modifying the style of html Element:


<html>
<head>
<script type="text/javascript">
document.writeln("<h1 style=\"color:green\">Welcome to JavaScript!</h1>");
</script>
</head>
<body>
</body>
</html>

• Note: The characters \" JavaScript allows large statements to be split over many lines. are not
displayed in the browser. The backslash (\) in a string is an escape character. It indicates that a
“special” character is to be used in the string. The escape sequence \" is the double-quote
character, which causes a double-quote character to be inserted into the string.

5
• We could also have used single quotes for the attribute value, as in document.write( "<h1 style
= 'color: magenta'>" );, because the single quotes do not terminate a double-quoted string.
<html>
<head>
<script type="text/javascript">
document.writeln("<h1 style='color:green\'>");
document.writeln("Welcome to JavaScript Programming!</h1>");
</script>
</head>
<body>
</body> </html>

3.2 DATA TYPES


• JavaScript is a dynamic type language. We don’t need to specify type of the variable
because it is dynamically used by JavaScript engine.
• JavaScript automatically determines the variables' data type .
• Use var or let to specify the data type. It can hold any type of values such as numbers,
strings etc.
var a=40;//holding number
var b="Rahul";//holding string
• There are eight basic data types in JavaScript. They are:

S.No. Data Description Example


Types
1 String String is used to store text. Strings are const name = 'ram';
surrounded by quotes: const name1 = "hari";
Single quotes: 'Hello' const result = `The names are
Double quotes: "Hello" ${name} and ${name1}
Backticks: `Hello`
const number1 = 3;
represents integer and floating numbers
const number2 = 3.433;
2 Number (decimals and exponentials
const number3 = 3e5 // 3 * 10^5
A number type can also be +Infinity, - const number1 = 3/0;

6
Infinity, and NaN (not a number). console.log(number1); // Infinity
const number2 = -3/0;
console.log(number2); // -Infinity
// strings can't be divided by
numbers
const number3 = "abc"/3;
console.log(number3); // NaN
3 BigInt Number type can only represent // BigInt value
numbers less than (253 - 1) and more const value1 =
than -(253 - 1). To use a larger number 900719925124740998n;
than that, you can use the BigInt data // Adding two big integers
type. const result1 = value1 + 1n;
A BigInt number is created by console.log(result1); //
appending n to the end of an integer. "900719925124740999n"
const value2 =
900719925124740998n;
// Error! BitInt and number
cannot be added
const result2 = value2 + 1;
console.log(result2);
4 Boolean Boolean represents one of two values: let a = true;
true or false let b=false;
5 undefined The undefined data type represents let name;
value that is not assigned. console.log(name); // undefined
If a variable is declared but the value let name = undefined;
is not assigned, then the value of that console.log(name); // undefined
variable will be undefined.
6 null In JavaScript, null is a special value that let name=null;
represents empty or unknown value.
7 Symbol A value having the data type Symbol // two symbols with the same
can be referred to as a symbol value. description
Symbol is an immutable primitive value const value1 = Symbol('hello');
that is unique. Symbol for unique const value2 = Symbol('hello');
7
identifiers. Though value1 and value2 both
contain 'hello', they are different as
they are of the Symbol type.
8 Object An object is a complex data type that const student = {
allows us to store collections of data. firstName: 'ram',
lastName: null,
class: 10
};

To find the type of a variable, we can use the typeof operator.

const name = 'ram';


typeof(name); // returns "string"

COMMENTS
The JavaScript comments adds information about the code, warnings or suggestions so that
end user can easily interpret the code.
The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the browser.
• Single-line Comment(//)
• Multi-line Comment(/* */)

3.3 VARIABLES
• A variable is a container (storage area) to hold data
• A variable is name of storage location.
• There are two types of variables in JavaScript: local variable and global variable.
• In JavaScript, we use either var or let keyword to declare variables. For example,
var x;
let y;
var is used in the older versions of JavaScript. var is function scope.
let is the new way of declaring variables starting ES6 (ES2015). let is block scoped
let num = 5; // num is a variable. It's storing 5.
Rules for Naming JavaScript Variables:
1. Variable names must start with either a letter, an underscore _, or the dollar sign $.
let a = 'hello';
let _a = 'hello';
8
let $a = 'hello';
2. Variable names cannot start with numbers
Let 1a = 'hello'; // this gives an error
3. JavaScript is case-sensitive. So y and Y are different variables. For example,
let y = "hi";
let Y = 5;
console.log(y); // hi
console.log(Y); // 5
4. Keywords cannot be used as variable name
Note: In JavaScript, the variable names are generally written in camelCase if it has multiple words.
For example, firstName, annualSalary

CONSTANTS
The const keyword was used to create a constant. Once a constant is initialized, we cannot
change its value.If value of a variable won't change throughout the program, it' recommended to
use const
const x = 5;
x = 10; // Error! constant cannot be changed.
console.log(x)

3.4 DIALOG BOXES


JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.
Alert Box
• An alert box is often used if we want to make sure information comes through to the user.
• When an alert box pops up, the user will have to click "OK" to proceed.
Syntax: alert("sometext");
<html>
<head>
<title>My First JavaScript code!!!</title>
<script type="text/javascript">
alert("Welcome!!!");
</script>
</head>
<body>
</body>
</html>
9
Confirm Box
• A confirm box is often used if you want the user to verify or accept something.
• When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.
• If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns
false.
Syntax: confirm("sometext");
<html>
<head>
<title>My First JavaScript code!!!</title>
<script type="text/javascript">
var r =confirm("Do you want to continue");
</script>
</head>
<body>
</body>
</html>

Prompt Box
• A prompt box is often used if you want the user to input a value before entering a page.
• When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed
after entering an input value.
• If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box
returns null.
<html>
<head>
<title>User Input with prompt dialog</title>
<script type="text/javascript">
var r =prompt("Enter your name");
document.writeln("Hello "+r);
</script>
</head>
<body>
</body>
</html>

10
<html>
<head>
<title>User Input with prompt dialog</title>
<script type="text/javascript">
var a=parseInt(prompt("Enter first number"));
var b=parseInt(prompt("Enter second number"));
var c=a+b;
document.write("<h1>Added Value="+c+"</h1>");
</script>
</head>
<body>
</body>
</html>

Example 2: Dialog box with event handling


<html>
<head>
<script type="text/javascript">
function show_alert()
{
alert("I am an alert box!");
}
</script>
</head>
<body>
<input type="button" onclick="show_alert()" value="Show alert box" />
</body>
</html>

Demo2:
<html>
<head>
<script type="text/javascript">
function show_confirm()
{
var r=confirm("Press a button");
if (r==true)
{
alert("You pressed OK!");
}
else
{
alert("You pressed Cancel!");
}
}
</script>
</head>
<body>
<input type="button" onclick="show_confirm()" value="Show confirm box" />
</body>
</html>
11
Prompt Demo1:
<html>
<head>
<script type="text/javascript">
function funadd()
{
let name=prompt("Enter your Name");
document.write("Welcome "+name);
}
</script>
</head>
<body>
<input type="button" onclick="funadd()" value="CLICK" />
</body>
</html>

Example 3: Addition using dialog box


<html>
<head>
<script type="text/javascript">
function funadd()
{
let a=parseInt(prompt("Enter Number1"));
let b=parseInt(prompt("Enter Number2"));
let c=a+b;
document.write("The sum is"+c);
}
</script>
</head>
<body>
<input type="button" onclick="funadd()" value="Add" />
</body>
</html>

12
3.5 OPERATORS
In JavaScript, an operator is a special symbol used to perform operations on operands.
For Example 2+3
Here + is an operator that performs addition, and 2 and 3 are operands.
The List of different operators
• Assignment Operators
• Arithmetic Operators
• Comparison Operators
• Logical Operators
• Bitwise Operators
• String Operators
• Other Operators
Arithmetic Operators
Arithmetic operators are used to perform arithmetic between variables and/or values. Given
that y=5, the table below explains the arithmetic operators:
Operator Description Example Result
+ Addition x=y+2 x=7
- Subtraction x=y-2 x=3
* Multiplication x=y*2 x=10
/ Division x=y/2 x=2.5
% Modulus (division remainder) x=y%2 x=1
++ Increment x=++y x=6
-- Decrement x=--y x=4
** Exponentiation (Power) x=y**2 x=25

Assignment Operators
Assignment operators are used to assign values to JavaScript variables. Given that x=10 and
y=5, the table below explains the assignment operators:
Operator Example Same As Result
= x=y x=5
+= x+=y x=x+y x=15
-= x-=y x=x-y x=5
*= x*=y x=x*y x=50
/= x/=y x=x/y x=2
%= x%=y x=x%y x=0

13
Comparison Operators
. Comparison operators compare two values and return a boolean value, either true or false.
Comparison operators are used in logical statements to determine equality or difference between
variables or values .Given that x=5, the table below explains the comparison operators.
Operator Description Example
== is equal to x==8 is false
=== is exactly equal to (value and type) x===5 is true
x==="5" is false
!= is not equal x!=8 is true
> is greater than x>8 is false
< is less than x<8 is true
>= is greater than or equal to x>=8 is false
<= is less than or equal to x<=8 is true

Logical Operators
Logical operators perform logical operations and return a boolean value, either true or false.
Logical operators are used in decision making and loops Given that x=6 and y=3, the table below
explains the logical operators:
Operator Description Example
&& and (x < 10 && y > 1) is true
|| or (x==5 || y==5) is false
! not !(x==y) is true

Bitwise Operators
Bitwise operators perform operations on binary representations of numbers.
Operator Description Example
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise NOT
<< Left shift
>> Sign-propagating right shift
>>> Zero-fill right shift

Other Operators
Operator Description Example
, evaluates multiple operands and returns the let a = (1, 3 , 4); // 4
value of the last operand.

?: returns value based on the condition (5 > 3) ? 'success' : 'error'; // "success"


14
delete deletes an object's property, or an element of delete x
an array
typeof returns a string indicating the data type typeof 3; // "number"
void discards the expression's return value void(x)
in returns true if the specified property is in the prop in object
object
instanceof returns true if the specified object is of of object instanceof object_type
the specified object type

Demo.html:
<html>
<head>
<script type="text/javascript">
let a=10,b=3,c=12;
let x=a<<2;
document.write("<h1>"+(a+b)+"</h1>");
document.write("<h1>"+(a>b)+"</h1>");
document.write("<h1>"+((a>b)&&(a>c))+"</h1>")
document.write("<h1>"+x+"</h1>")
a+=2
document.write("<h1>"+a+"</h1>")
document.write(a);
</script>
</head>
<body>
</body>
</html>

3.6 CONDITIONAL STATEMENT


To perform different actions for different decisions. We can use conditional statements in our
code to perform different operations.
In JavaScript we have the following conditional statements:
• if statement - use this statement to execute some code only if a specified condition is true
• if...else statement - use this statement to execute some code if the condition is true and
another code if the condition is false
• if...else if....else statement - use this statement to select one of many blocks of code to be
executed
• switch statement - use this statement to select one of many blocks of code to be executed

15
If Statement
• if statement to execute some code only if a specified condition is true.
• If the condition is evaluated to true, the code inside the body of if is executed.
• If the condition is evaluated to false, the code inside the body of if is skipped.

Syntax
if (condition)
{
code to be executed if condition is true
}
If...else Statement
• Use the if....else statement to execute some code if a condition is true and another code if the
condition is not true.
• If the condition is evaluated to true, the code inside the body of if is executed.
• If the condition is evaluated to false, the code inside the body of if is skipped.
Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Example:
<html>
<head>
<script type="text/javascript">
let mark=15;
if(mark>=50)
{
document.write("<h1> Ur mark is"+mark+"</h1>");
document.write("<h1> Pass </h1>");
}
else
{
document.write("<h1> Ur mark is"+mark+"</h1>");
document.write("<h1> Fail</h1>");
}
</script>
16
</head>
<body>
</body>
</html>

If...else if...else Statement

• Use the if....else if...else statement to select one of several blocks of code to be executed.
• The if...else statement is used to execute a block of code among two alternatives. However, if
you need to make a choice between more than two alternatives, if...else if...else can be used.
Syntax
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true }
else
{
code to be executed if condition1 and condition2 are not true }
If condition1 evaluates to true, the code block 1 is executed.
If condition1 evaluates to false, then condition2 is evaluated.
If the condition2 is true, the code block 2 is executed.
If the condition2 is false, the code block 3 is executed.
Example:
<html>
<head>
<script type="text/javascript">
let a =10,b=20,c=80;
if((a>b)&&(a>c))
document.writeln("<h1>"+a+" is greater</h1>");
else if(b>c)
document.writeln("<h1>"+b+" is greater</h1>");
else
document.writeln("<h1>"+c+" is greater</h1>");
17
</script>
</head>
<body>
</body>
</html>

Nested if...else Statement


• We can also use an if...else statement inside of an if...else statement. This is known as nested
if...else statement.
• Nested if...else makes our logic complicated and we should try to avoid using nested if...else
whenever possible.
• If the body of if...else has only one statement, we can omit { } in our programs. For
example, you can replace
The JavaScript Switch Statement
• Use the switch statement to select one of many blocks of code to be executed.
• The JavaScript switch statement is used in decision making.
• The switch statement evaluates an expression and executes the corresponding body that
matches the expression's result.
The switch statement evaluates a variable/expression inside parentheses ().
o If the result of the expression is equal to value1, its body is executed.
o If the result of the expression is equal to value2, its body is executed.
o This process goes on. If there is no matching case, the default body executes.

Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
The break statement is optional. If the break statement is encountered, the switch statement ends.

18
If the break statement is not used, the cases after the matching case are also executed.
The default clause is also optional.
Demo.html
<html>
<head>
<script type="text/javascript">
let num1,num2,res,c;
num1=parseFloat(prompt ('Enter the first number: '));
num2=parseFloat(prompt ('Enter the Second number: '));
c=parseInt(prompt ('Enter the operation \n1.Add\n 2.Sub\n3.Mul\n4.Div\n5.Mod'));
switch(c)
{
case 1:
res=num1+num2;
window.alert(" Result is: " + res);
break;
case 2:
res=num1-num2;
window.alert(" Result is :" + res);
break;
case 3:
res=num1*num2;
window.alert(" Result is: " + res);
break;
case 4:
res=num1/num2;
window.alert(" Result is :" + res);
break;
case 5:
res=num1%num2;
window.alert(" Result is :" + res);
break;
}

19
</script> </head> <body> </body> </html>

3.7 ITERATION
Often when we write code, we want the same block of code to run over and over again in a row.
Instead of adding several almost equal lines in a script we can use loops to perform a task like this.
In JavaScript, there are two different kind of loops:
• for - loops through a block of code a specified number of times
• while - loops through a block of code while a specified condition is true
The for Loop
The for loop is used when you know in advance how many times the script should run.
Syntax
for (variable=startvalue;variable<=endvalue;variable=variable+increment)
{
code to be executed }
Example
The example below defines a loop that starts with i=0. The loop will continue to run as long as i is
less than, or equal to 5. i will increase by 1 each time the loop runs.
20
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=5;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

JavaScript While Loop


Loops execute a block of code a specified number of times, or while a specified condition is true.
The while Loop
The while loop loops through a block of code while a specified condition is true.
Syntax
while (variable<=endvalue)
{
code to be executed
}
Example
The example below defines a loop that starts with i=0. The loop will continue to run as long as i is
less than, or equal to 5. i will increase by 1 each time the loop runs:
Example
<html>
<body>
<script type="text/javascript">
var i=0;
while (i<=5)
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
</script> </body> </html>
Example: Finding the sum and average of 5 numbers
<html>
<head>
<script type="text/javascript">

21
let tot=0,i=1;
while(i<=5)
{
num=parseInt(prompt("Enter the number"));//54,56,78,45,32
tot=tot+num;
i++;
}
let avg=tot/5;
document.write("The Total is"+tot);//265
document.write("The Avg is"+avg);//53
</script>
</head>
<body>
</body>
</html>

The do...while Loop


The do...while loop is a variant of the while loop. This loop will execute the block of code ONCE,
and then it will repeat the loop as long as the specified condition is true.
Syntax
do
{
code to be executed
}
while (variable<=endvalue);
Example
The example below uses a do...while loop. The do...while loop will always be executed at least
once, even if the condition is false, because the statements are executed before the condition is
tested:
<html>
<body>
<script type="text/javascript">
var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
while (i<=5);
</script>
</body>
</html>
22
The break Statement
The break statement will break the loop and continue executing the code that follows after the loop
Example
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

The continue Statement


The continue statement will break the current loop and continue with the next value.
Example
<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

JavaScript For...In Statement


The for...in statement loops through the elements of an array or through the properties of an object.
Syntax
for (variable in object)
{ code to be executed }

23
Note: The code in the body of the for...in loop is executed once for each element/property.
Note: The variable argument can be a named variable, an array element, or a property of an object.
Example
<html>
<body>
<script type="text/javascript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
for (x in mycars)
{
document.write(mycars[x] + "<br />");
}
</script>

</body>
</html>

3.8 ARRAYS
An array is a special variable, which can hold more than one value at a time. Arrays in
javascript can store any datatype inside. Java script supplies a native function object named Array
that can be used to construct objects.
Creating an Array
i) Using Array constructor directly
syntax
var varname=new Array();
var a=new Array();

ii) Array can be constructed and initialized with values suppling two or more arguments to an
array constructor
var a1=new Array(4,true,”ok”); (or) var a1=[4,true,”ok”];
Then a1[0] have number 4,a1[1] have Boolean value true and a1[3] have a string value “ok”.
Every Array object given a special property named length
a1.length is 3.
Length: number of elements in an array

24
Example1
<html>
<head>
<title>JAva script</title>
</head>
<body>
<script type="text/javascript">
var a1=[4,true,"ok"];
for (x in a1)
{
document.write(a1[x] + "<br />");
}
</script>
</body>
</html>

Example2
<html>
<head>
<title>JAva script</title>
</head>
<body>
<script type="text/javascript">
var a1=[4,true,"ok"];
for (i=0;i<3;i++)
{
document.write(a1[i] + "<br />");
}
</script>
</body>
</html>

Example
Use the for...in statement to loop through an array:
<html>
<body>
<script type="text/javascript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
for (x in mycars)
25
{ document.write(mycars[x] + "<br />");
}
</script>
</body>
</html>

To Store multidimensional array


Var matrix=[
[1,2,3,],
[4,5,6],
[7,8,9]
]
Points in Array Object
i) The length property of Array object can be changed.
Ex: a1[3]=12
<html>
<head>
<title>JAva script</title>
</head>
<body>
<script type="text/javascript">
var a1=[4,true,"ok"];
document.write("The array length"+ a1.length + "<br />");
a1[3]=12;
for (i=0;i<=3;i++)
{
document.write(a1[i] + "<br />");
}
document.write("The array length"+a1.length + "<br />");
</script>
</body>
</html>

ii) Elements can also be removed from a javascript array by decreasing the value of length
property
a1.length=2;
<html>
<head>
<title>JAva script</title>
26
</head>
<body>
<script type="text/javascript">
var a1=[4,true,"ok"];
document.write("The array length"+ a1.length + "<br />");
a1[3]=12;
a1.length=2;
for (i=0;i<=3;i++)
{
document.write(a1[i] + "<br />");
}
document.write("The array length"+a1.length + "<br />");
</script>
</body>
</html>

iii) If we increase the length of an Array object, it does not automatically add any elements
to the array.
iv) var a1=new Array(200).It creates an array having length 200.

Array methods:
Method Description
concat() Returns a new array comprised of this array joined with other array(s) and/or value(s).
join() Joins all elements of an array into a string.
pop() Removes the last element from an array and returns that element.
push() Adds one or more elements to the end of an array and returns the new length of the
array.
reverse() Reverses the order of the elements of an array -- the first becomes the last, and the
last becomes the first.
shift() Removes the first element from an array and returns that element.
slice() Extracts a section of an array and returns a new array.
sort() Sorts the elements of an array
splice() Adds and/or removes elements from an array.

i) concat():
Returns a new array comprised of this array joined with two or more arrays.
<html>
<body>
<script>
var arr1=["C","C++","Python"];

27
var arr2=["Java","JavaScript","Android"];
var result=arr1.concat(arr2);
document.writeln(result);
</script>
</body>
</html>

ii) join():
join() method joins all the elements of an array into a string.
<html>
<body>
<script>
var arr=["AngularJs","Node.js","JQuery"]
var result=arr.join("-")
document.write(result);
</script>
</body>
</html>

iii) push(anytype), pop(),shift() methods used to implement stack and queue data structure .
push (anytype):add elements at top of stack or end of queue.
var stack=new Array();
stack.push(“A”);
stack.push(“M”);
pop():removes last element.
var c=stack.pop();
var c1=stack.pop();
<html>
<head>
<title>JAva script</title>
</head>
<body>
<script type="text/javascript">
var a=new Array();
a.push(10);
a.push(20);
a.push(30);
document.write(a.toString()+"<br/>");
var b1=a.pop();
document.write(b1+"<br/>");
var b2=a.pop();
document.write(b2+"<br/>");
var b3=a.pop();
28
document.write(b3+"<br/>");
</script>
</body>
</html>

shift():removes the first element used in Queue and shifts all remaining element down one index.It
returns value of element removed.
<html>
<head>
<title>JAva script</title>
</head>
<body>
<script type="text/javascript">
var a=new Array();
a.push(10);
a.push(20);
a.push(30);
document.write(a.toString()+"<br/>");
var b1=a.shift();
document.write(b1+"<br/>");
var b2=a.shift();
document.write(b2+"<br/>");
var b3=a.shift();
document.write(b3+"<br/>");
</script>
</body>
</html>

iv) reverse() - Puts array elements in reverse order.


<html>
<head>
<title>JAva script</title>
</head>
<body>
<script type="text/javascript">
words = new Array("limit","lines","finish","complete","In","Out");
document.write(words+"<br/>");
document.write(words.reverse());
</script>
</body>
</html>

29
v) splice
a) splice (number, 0, anytype)
Inserting third argument as an element at the index given by first argument, shifting elements up
one index, to make a room for new element.
var num=[1,9,4,2];
num.splice(2,0,3);
num.toString();
Example
<html>
<head>
<title>JAva script</title>
</head>
<body>
<script type="text/javascript">
var a1=[1,2,3,4,5,6,7,8];
a1.splice(3,0,77);
document.writeln(a1.toString());
</script>
</body>
</html>

Example1:
<html>
<head>
<title>JAva script</title>
</head>
<body>
<script type="text/javascript">
var a1=[1,2,3,4,5,6,7,8];
a1.splice(3,1,77);
document.writeln(a1.toString());
</script>
</body>
</html>

b) splice(number, number)
Removes a number of elements specified by second argument starting with the index
specified by first argument and returns array of elements removed.

30
<html>
<head> <title>JAva script</title>
</head>
<body>
<script type="text/javascript">
var a1=[1,2,3,4,5,6,7,8];
a1.splice(3,1,77);
document.writeln(a1.toString());
a1.splice(3,4);
document.writeln("<br>"+a1.toString());
</script>
</body>
</html>

vi) slice():
slice() method extracts a section of an array and returns a new
array.
<html>
<body>
<script>
var
arr=["AngularJS","Node.js","JQuery","Bootstrap"]
var result=arr.slice(0,2);
document.writeln(result);
</script>
</body>
</html>

vii) sort()
sort() method sorts the elements of an array.
array.sort( compareFunction );
compareFunction − Specifies a function that defines the sort order. If omitted, the array is sorted
lexicographically.
Example:
<html>
<head>
<script type="text/javascript">
let a=[43,84,6,12,78];
let res=a.sort();
document.write(res);
a.sort(function
compare(first,second)
{
31
return first-second;
});
document.write("</br>"+a);
</script>
</head>
<body>
</body>
</html>

Example:
<html>
<body>
<script>
var arr=["AngularJS","Node.js","JQuery","Bootstrap"]
var result=arr.sort();
document.writeln(result);
</script>
</body>
</html>

3.9 FUNCTIONS:
• A function is a block of code or set of statements that performs a specific task.
Advantages of JavaScript functions. Code reusability, less coding and modularity, Function
increases readability.
Two types
i) built-in function example alert,prompt,confirm
ii) user-defined functions
Syntax for user defined function
//defining a function
function functionName(Parameter1, Parameter2, ..)
{
// Function body
}//calling a function
function-name(args);
Function Definition:
Every function should begin with the keyword function followed by,
A user defined function name which should be unique,
A list of parameters enclosed within parenthesis and separated by commas,
• A JavaScript function can be defined using function keyword.
32
• JavaScript Functions can have 0 or more arguments.
• All variables declared in function definitions are local variables—this means that they can
be accessed only in the function in which they are defined.
Function call
• A function is invoked by a function call.
• The function call specifies the function name and provides information (as arguments) that
the called function needs to perform its task.
• Most functions have a list of parameters that provide the means for communicating
information between functions via function calls. A function’s parameters are also
considered to be local variables. When a function is called, the arguments in the function
call are assigned to the corresponding parameters in the function definition.
functionName( Value1, Value2, ..);
return Statement: function returns some values from a function after performing some operations.
The return statement can be used to return the value to a function call.
The return statement denotes that the function has ended. Any code after return is not executed.
If nothing is returned, the function returns an undefined value.
Four Types of function
i) function with no argument and no return type
ii) function with no argument and return type
iii) function with argument and no return type
iv) function with argument and return type
i) function with no argument and no return type
<html>
<head>
<script type="text/javascript">
function add()
{
let a=10,b=5;
c= a+b;
document.write("The result is"+c);
}
add();
</script>
</head>
<body> </body> </html>

33
ii) function with argument and no return type
<html>
<head>
<script type="text/javascript">
function add(a,b)
{
c= a+b;
document.write("The result is"+c);
}
add(5,9);
</script>
</head>
<body> </body> </html>

iii) function with no argument and return type


<html>
<head>
<script type="text/javascript">
function add()
{
let x=9,y=8;
return x+y;
}
let res=add();
document.write("The result is"+res)
</script> </head> <body> </body> </html>
iv) function with argument and return type
<html>
<head>
<script type="text/javascript">
function add(a,b)
{
return a+b;
}
let res=add(5,6);
document.write("The result is"+res)
</script>
</head>
<body>
</body>
</html>

34
3.9.1 Expression Function
In Javascript, functions can also be defined as expressions. And the function is called using
the variable name.The function is called an anonymous function.
An anonymous function can be defined as a function without a name. The anonymous function does
not bind with an identifier. It can be declared dynamically at runtime. The anonymous function is
not accessible after its initial creation.
An anonymous function can be assigned within a variable. Such expression is referred to as
function expression. The syntax for the anonymous function is as follows.
var function_name = function( arguments )
{
//code to be executed
}
<html>
<head>
<script type="text/javascript">
let add= function()
{
let a=10,b=7;
let c=a+b;
document.write("The Sum is"+c);
}
add();
</script>
</head>
<body> </body> </html>

3.9.2 Arrow Function


Arrow function is one of the features introduced in the ES6 version of JavaScript. It allows
us to create functions in a cleaner way compared to regular functions. They allow us to write
smaller function syntax. Arrow functions make out code more readable and structured.
Arrow functions are anonymous functions. They don't return any value and can declare without the
function keyword.
They are also called as Lambda Functions
// function expression
let x = function(x, y) {
return x * y; }
can be written as // using arrow functions

35
let x = (x, y) => x * y;
The syntax
let myFunction = (arg1, arg2, ...argN) => {
statement(s)
}
myFunction is the name of the function
arg1, arg2, ...argN are the function arguments
Fat arrow notation/lambda notation: It is the notation for the arrow (=>).
statement(s) is the function body

Arrow Function with No Argument


If a function doesn't take any argument, then you should use empty parentheses. For example,
let greet = () => console.log('Hello');
greet(); // Hello
Example 2: Arrow Function with One Argument
If a function has only one argument, you can omit the parentheses. For example
let greet = x => console.log(x);
greet('Hello'); // Hello

Multiline Arrow Functions


If a function body has multiple statements, you need to put them inside curly brackets {}.
For example,
let sum = (a, b) => {
let result = a + b;
return result;
}
let result1 = sum(5,7);
console.log(result1); // 12

Example: With all types of functions


<html>
<head>
<script type="text/javascript">
function greet() //normal function

36
{
return "hello";
}
let greet1= function() //anonymous function
{
return "hello";
}
let greet2=()=> "hello" // arrow function with no argument
let greet3=x=>document.writeln(x);//arrow function with argumeent
let str1=greet();
document.writeln(str1);
let str2=greet1();
document.writeln(str2);
let str3=greet2();
document.writeln(str3);
greet3("Hello");
</script>
</head>
<body>
</body>
</html>

Example: Addition With all types of functions


<html>
<head>
<script type="text/javascript">
function add(a,b) //normal function
{
return a+b;
}
let add1= function(a,b) //anonymous function
{
return a+b;
}
let add2=(a,b)=> document.writeln("Sum is"+(a+b));//arrow function with argument
let res1=add(2,3);
document.writeln("Sum is"+res1);
let res2=add1(4,3);
document.writeln("Sum is"+res2);
add2(9,3);
</script>
</head>
<body>
</body>
</html>

37
3.9.3 Functions: REDUCE, SPREAD, REST
JS ES6 has some great features that make working with function parameters and arrays
extremely easy.
reduce():
• The reduce() method executes a user-supplied "reducer" callback function on each element of
the array, in order, passing in the return value from the calculation on the preceding element.
The final result of running the reducer across all elements of the array is a single value.
• The reduce() method executes a reducer function for array element.
• The reduce() method returns a single value: the function's accumulated result.
• The reduce() method does not execute the function for empty array elements.
• The reduce() method does not change the original array.
Syntax:
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

Reducer function parameters:


total Required.
The initialValue, or the previously returned value of the function.
currentValue Required.
The value of the current element.
currentIndex Optional.
The index of the current element.
arr Optional.
The array the current element belongs to.
Example: // This is used to subtract all elements in an array
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>Subtract the numbers in the array, starting from the left:</p>
<script>
const numbers = [175, 50, 25];
let a=numbers.reduce(myFunc);
function myFunc(total, num) {
return total - num;
}
document.writeln(a);
</script>
</body>
</html>
Output: 100

38
rest and spread:
JavaScript uses three dots (...) for both the rest and spread operators. But these two operators
are not the same.
Rest:
The rest parameter syntax allows a function to accept an indefinite number of arguments as an
array.The three dots(…) can be included in the function definition followed by the name of the
array .
Syntax:
function f(...theArgs) {
// …
}
Program1:
<html>
<head>
<script type="text/javascript">
function sum(...args)
{
console.log(args);
}
sum(4,2,6,29);
</script>
</head>
<body>
</body>
</html>

Program2:
<html>
<head>
<script type="text/javascript">
//rest parameter
function sum(...theArgs) {
let total = 0;
for (const arg of theArgs) {
total += arg;
}
return total;
}
let res=sum(4,2,6,29);
39
document.write(res);
</script>
</head>
<body>
</body>
</html>

SPREAD
• The spread operator (...) helps to expand iterables such as array or string, into individual
elements. Spread syntax "expands" an array into its elements.
• rest syntax collects multiple elements and "condenses" them into a single element.
• It is used in the function call
Example:
<html>
<head>
<script type="text/javascript">
//spread parameter
function sum(a,b,c,d,e)
{
return a+b+c+d+e;
}
let nums=[4,5,6,2,1]; //pass an array and individual elemnt of parameteers in fd
let res=sum(...nums); //spread operator
document.write(res);
</script> </head>
<body> </body> </html>
Output:18

3.10 EVENT HANDLING


• The change in the state of an object is known as an Event.
• An event is a notification that something specific has occurred, either with the browser, such as
the completion of the loading of a document, or because of a browser user action, such as a mouse
click on a form button.
• In html, there are various events which represents that some activity is performed by the user or
by the browser.
• When JavaScript code is included in HTML, Java Script reacts over these events and allow the
execution.
• This process of reacting over the events is called Event Handling.
40
• Thus JavaScript handles the HTML events via Event Handlers.
• JavaScript functions are normally not called directly from the top level of a JavaScript program.
Instead, functions are called in response to various user actions, such as clicking a button or moving
the mouse over a certain element.
• An intrinsic event attributes is used to provide scripting code that is called when a particular
event associated with the element containing the attribute occurs. Finally, the name of each event
attribute is on followed by the name of the associated event.
• An event handler is a script that is implicitly executed in response to the appearance of an event.
• Event handlers enable a Web document to be responsive to browser and user activities. To react
on events we can assign a handler – a function that runs in case of an event. Handlers are a way to
run JavaScript code in case of user actions.
There are 3 ways to assign event handlers:
i. HTML attribute: onclick="...".
ii. DOM property: elem.onclick = function.
iii. Methods: elem.addEventListener(event, handler[, phase]) to add, removeEventListener to
remove.
• One of the most common uses of event handlers is to check for simple errors and omissions
in user input to the elements of a form, either when they are changed or when the form is
submitted. This kind of checking saves the time of sending incorrect form data to the server.
Events and their tag attributes Events, Attributes, and Tags

41
i) HTML attribute:
• A handler can be set in HTML with an attribute named on<event>. For instance, to assign a
click handler for an input, we can use onclick
• HTML allows event handler attributes, with JavaScript code, to be added to HTML
elements.
With single quotes: <element event='some JavaScript'>
With double quotes: <element event="some JavaScript">

Demo1:
<html>
<head>
<script>
function show()
{
alert('Click! Hello');
}
</script>
</head>
<body>
<input type="button" value="Click me" onclick="show()" >
<body>
</html>

Demo2:
<html>
<head>
<script>
function displayDate()
{
const d = new Date();
document.write(d);
}
</script>
</head>
<body>
<button onclick="displayDate()">Click here to View the Time</button>
<body>
</html>

42
Disadvantages of using HTML event handler attributes
• First, the event handler code is mixed with the HTML code, which will make the code more
difficult to maintain and extend.
• Second, it is a timing issue. If the element is loaded fully before the JavaScript code, users
can start interacting with the element on the webpage which will cause an error.
• It is impossible to call more than one function for the same one event.

ii) DOM property:


• We can also assign and set up event handlers to elements using scripting, and inside our
script .
• This allows for the event handlers to be dynamically set up, without having to mess
around with the HTML codes on the page.
• When setting up event handlers for an element directly inside our script, the code to
execute for the events must be defined inside a function.
elem.onclick = function.
An event handler function could also be registered by assigning its name to the
associated event property on the button object.
Demo1
<html >
<head>
<title>JavaScript Assigning Multiple Event Handlers on a Single Event</title>
</head>
<body>
<input type="button" value="Click here" id="myBtn"/>
<script>
// Defining custom functions
function firstFunction() {
alert("The first function executed successfully!");
}
// Selecting button element
var btn = document.getElementById("myBtn");
// Assigning event handlers to the button
btn.onclick=firstFunction;
</script>
</body>
</html>

43
iii) The addEventListener() method attaches an event handler to an element.
We created more than one functions and can execute both of them on click of the button
using the onclick event handler.
element.addEventListener (event, function, useCapture)
event :name of the event .Do not use the "on" prefix. Use "click" not "onclick".
Function : Required. The function to run when the event occurs. useCapture Optional (default
= false).
false - The handler is executed in the bubbling phase.
true - The handler is executed in the capturing phase.
Eg:
element.addEventListener("mouseover", myFunction);
element.addEventListener("click", someOtherFunction);
element.addEventListener("mouseout", someOtherFunction);
Demo1:
<html >
<head>
<title>JavaScript Assigning Multiple Event Handlers on a Single Event</title>
</head>
<body>
<button id="myBtn">Click Me</button>
<script>
function firstFunction() { // Defining custom functions
alert("The first function executed successfully!");
}
function secondFunction() {
alert("The second function executed successfully");
}
var btn = document.getElementById("myBtn"); // Selecting button element
btn.addEventListener("click", firstFunction); // Assigning event listeners to the button
btn.addEventListener("click", secondFunction);
</script> </body> </html>

44
Event Bubbling or Event Capturing
• There are two ways of event propagation in the HTML DOM, bubbling and capturing.
• Event propagation is a way of defining the element order when an event occurs.
• If <p> element inside a <div> element, and the user clicks on the <p> element, which
element's "click" event should be handled first?
o In bubbling the inner most element's event is handled first and then the outer:
the <p> element's click event is handled first, then the <div> element's click event.
o In capturing the outer most element's event is handled first and then the inner:
the <div> element's click event will be handled first, then the <p> element's click event.
• With the addEventListener() method we can specify the propagation type by using the
"useCapture" parameter:
addEventListener(event, function, useCapture);
The default value is false, which will use the bubbling propagation, when the value is set to
true, the event uses the capturing propagation.
Bubbling
<html>
<head>
<style>
#myDiv1 {
background-color: coral;
padding: 50px;
}
#myP1{
background-color: white;
font-size: 20px;
border: 1px solid;
padding: 20px;
}
</style>
</head>
<body>
<div id="myDiv1">
<h2>Bubbling:</h2>
<p id="myP1">Click me!</p>
</div><br>
<script>
function show() {
alert("You clicked the white element!");

45
}
function show1() {
alert("You clicked the orange element!");
}
document.getElementById("myP1").addEventListener("click",show, false);
document.getElementById("myDiv1").addEventListener("click", show1, false);
</script>
</body>
</html>

Capturing
<html>
<head>
<style>
#myDiv1 {
background-color: coral;
padding: 50px;
}
#myP1{
background-color: white;
font-size: 20px;
border: 1px solid;
padding: 20px;
}
</style>
</head>
<body>
<div id="myDiv1">
<h2>Bubbling:</h2>
<p id="myP1">Click me!</p>
</div><br>
<script>
function show() {
alert("You clicked the white element!");
}
function show1() {
alert("You clicked the orange element!");
}
document.getElementById("myP1").addEventListener("click",show, true);
document.getElementById("myDiv1").addEventListener("click", show1, true);
</script>
</body> </html>

46
3.11 OBJECTS
• JavaScript is an Object Oriented Programming (OOP) language
• Object-oriented programmers concentrate on creating their own user-defined types called
classes.
• Each class contains data as well as the set of functions that manipulate that data and provide
services to clients (i.e., other classes or functions that use the class).
• The data components of a class are called properties.
• For example, a bank account class might include an account number and a balance. The
function components of a class are called methods.
Object Properties:
objectName.objectProperty = propertyValue;
Eg: var str = document.title;
Object Methods: document.write("This is test");
User-Defined Objects
var employee = new Object();
var books = new Array("C++", "Perl", "Java");
var day = new Date("August 15, 1947");
Demo:
<html>
<head> <title>User-defined objects</title>
<script type="text/javascript">
function addPrice(amount){
this.price = amount; }
function book(title, author){
this.title = title;
this.author = author;
this.addPrice = addPrice; }
</script> </head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body> </html>

47
3.11.1 BUILT-IN OBJECTS
i) Math Object
The Math object’s methods allow you to perform many common mathematical calculations.
The math object provides you properties and methods for mathematical constants and functions.
document.writeln( Math.sqrt( 900.0 ) );
Properties:
Property Description
PI Ratio of the circumference of a circle to its diameter, approximately 3.14159.
SQRT2 Square root of 2, approximately 1.414.

Methods:
Method Description
abs() Returns the absolute value of a number.
ceil() Returns the smallest integer greater than or equal to a number.
cos() Returns the cosine of a number.
exp() Returns EN, where N is the argument, and E is Euler's constant, the base of the
natural logarithm.
floor() Returns the largest integer less than or equal to a number.
max() Returns the largest of zero or more numbers.
min() Returns the smallest of zero or more numbers.
pow() Returns base to the exponent power, that is, base exponent.
random() Returns a pseudo-random number between 0 and 1.
round() Returns the value of a number rounded to the nearest integer.
sqrt() Returns the square root of a number.

Example:
<html>
<head>
<title>JavaScript Math Method</title>
</head>
<body>
<script type="text/javascript">
var value = Math.abs(-1);
document.writeln("First Test Value : " + value );
document.writeln(Math.sqrt(4));
document.writeln(Math.min(4,3));
document.writeln(Math.max(4,3));
document.writeln(Math.floor(4.1));
document.writeln(Math.ceil(4.1));
document.writeln(Math.pow(2,4)); </script> </body> </html>

48
ii) Date Object
• JavaScript’s Date object provides methods for date and time manipulations.
• Date and time processing can be performed based on the computer’s local time zone or
based on World Time Standard’s Coordinated Universal Time (abbreviated UTC)—
formerly called Greenwich Mean Time (GMT). Most methods of the Date object have a
local time zone and a UTC version.
• Date objects are created with the new Date() constructor.
o new Date()
o new Date(milliseconds)
o new Date(dateString)
o new Date(year, month, day, hours, minutes, seconds, milliseconds)
Methods:
Method Description
getDate() Get the day as a number (1-31)
getDay() Get the weekday as a number (0-6)
getFullYear() Get the four digit year (yyyy)
getHours() Get the hour (0-23)
getMilliseconds() Get the milliseconds (0-999)
getMinutes() Get the minutes (0-59)
getMonth() Get the month (0-11)
getSeconds() Get the seconds (0-59)
getTime() Get the time (milliseconds since January 1, 1970)
toString() Returns a string representing the specified Date object.

To display the current date:


<html>
<head>
<title>JavaScript Date Method</title>
</head>
<body>
<script>
var date=new Date();
var day=date.getDate();
var month=date.getMonth()+1;
var year=date.getFullYear();
document.write("<br>Date is: "+day+"/"+month+"/"+year);
49
</script>
</body>
</html>
Output: Date is: 15/10/2022

To display the current time:


<html>
<head>
<title>JavaScript Date Method</title>
</head>
<body>
<script>
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
document.write(h+":"+m+":"+s);
</script>
</body>
</html>
Output: 11:43:7

iii) String Object


• The String object encapsulates the attributes and behaviors of a string of characters.
• It provides many methods (behaviors) that accomplish useful tasks such as selecting
characters from a string, combining strings (called concatenation), obtaining substrings of a
string, searching for substrings within a string, tokenizing strings (i.e., splitting strings into
individual words) and converting strings to all uppercase or lowercase letters
• The JavaScript string is an object that represents a sequence of characters.
There are 2 ways to create string in JavaScript
By string literal
<script>
var str="This is string literal";
document.write(str);
</script>
By string object (using new keyword)
<script>
var stringname=new String("hello javascript string");

50
document.write(stringname);
</script>
Methods:
Methods Description
charAt() It provides the char value present at the specified index.
charCodeAt() It provides the Unicode value of a character present at the specified index.
concat() It provides a combination of two or more strings.
indexOf() It provides the position of a char value present in the given string.
lastIndexOf() It provides the position of a char value present in the given string by
searching a character from the last position.
search() It searches a specified regular expression in a given string and returns its
position if a match occurs.
match() It searches a specified regular expression in a given string and returns that
regular expression if a match occurs.
replace() It replaces a given string with the specified replacement.
substr() It is used to fetch the part of the given string on the basis of the specified
starting position and length.
substring() It is used to fetch the part of the given string on the basis of the specified
index.
slice() It is used to fetch the part of the given string. It allows us to assign positive as
well negative index.
toLowerCase() It converts the given string into lowercase letter.
toLocaleLowerCase() It converts the given string into lowercase letter on the basis of host?s current
locale.
toUpperCase() It converts the given string into uppercase letter.
toLocaleUpperCase() It converts the given string into uppercase letter on the basis of host?s current
locale.
toString() It provides a string representing the particular object.
valueOf() It provides the primitive value of string object.
split() It splits a string into substring array, then returns that newly created array.
trim() It trims the white space from the left and right side of the string.

51
<html>
<head>
<title>JavaScript toString() Method</title>
</head>
<body>
<script>
var str="javascript";
document.writeln(str.charAt(2));
var s2="concat example";
var s3=str.concat(s2);
document.writeln("<br>concatenated String "+s3);
document.writeln("<br>toLowerCase() "+str.toLowerCase());
document.writeln("<br>toUpperCase() "+str.toUpperCase());
document.writeln("<br>slice() "+str.slice(2,5));
</script>
</body>
</html>

iv) Boolean and Number Objects


• JavaScript provides the Boolean and Number objects as object wrappers for boolean true/ false
values and numbers, respectively.
• These wrappers define methods and properties useful in manipulating boolean values and
numbers.
• When a JavaScript program requires a boolean value, JavaScript automatically creates a
Boolean object to store the value. JavaScript programmers can create Boolean objects explicitly
with the statement
• Is an object that represents value in two states: true or false
• Boolean b=new Boolean(value);
• JavaScript automatically creates Number objects to store numeric values in a Java-
Script program. JavaScript programmers can create a Number object with the statement
var n = new Number( numericValue );
• The constructor argument numericValue is the number to store in the object. Although
we can explicitly create Number objects, normally the JavaScript interpreter creates them
as needed.
v) document Object
• The document object is used to manipulate the document that is currently visible in the
browser window. The document object has many properties and methods, such as methods
document.write() and document.writeln()

52
vi) GLOBAL OBJECT
• The global object provides variables and functions that are available anywhere. By default,
those that are built into the language or the environment.
• Objects in JavaScript are different from the Global Object. Using the new operator, we
cannot create global objects. It comes into existence when the scripting engine is initialized.
After it is initialized, the functions and constants are available for use.
• A global object allows you to do the following −
i) It gives access to built-in functions and values. Call alert directly like the below code
snippet, with window –
alert("Demo Text");
// or
window.alert("Demo Text");
ii) It also gives access to global function declarations and var variables –
<html>
<head>
<script>
var str = "Demo Text";
// using window
alert( window.str );
</script>
</head>
<body>
</body>
</html>

53
alert("Hello"); // is the same as window.alert("Hello");
In a browser, global functions and variables declared with var (not let/const!) become the property
of the global object:
var gVar = 5;
alert(window.gVar); // 5 (became a property of the global object)

vii) window Object


• The window object represents an open window in a browser.
• If a document contain frames (<frame> or <iframe> tags), the browser creates one window
object for the HTML document, and one additional window object for each frame.
Window Object Methods
• alert(String): Display alert window displaying the given String value.
• confirm(String): Pop up a window that displays the given String value and contains two
buttonslabeled OK and Cancel. Return boolean indicating which button was pressed(true
implies that OK was pressed).
• prompt(String,String): pop up a window that displays the first String value and contains a
text field andtwo buttons labeled OK and Cancel. Second String argument is initial valuethat
will be displayed in the text field. Return String representing final valueof text field if OK is
pressed, or null/undefined (browser-dependent) if Cancel button is pressed.
• open(String,String): Open a new browser window, and load the URI specified by the first
Stringargument into this window. The second String specifies a name for thiswindow suitable
for use as the value of a target attribute in an HTMLanchor or form element.
• close(): Close the browser window executing this method.
• focus(): Give the browser window executing this method the focus.
• blur(): Cause the browser window executing this method to lose the focus. Thewindow that
gains the focus is determined by the operating system.
• moveTo(Number,Number): Move the upper left corner of the browser window executing this
method to the(x, y) screen location (in pixels) specified by the argument values, whichshould
be integers. The upper left corner of the screen is at (0, 0).
• moveBy(Number,Number): Move the upper left corner of the browser window executing this
method rightand down by the number of pixels specified by the first and second,respectively,
argument values. These values should be integers.

54
• resizeTo(Number,Number): Resize the browser window executing this method so that it has
width andheight in pixels as specified by the first and second, respectively, argumentvalues.
These values should be integers.
• resizeBy(Number,Number): Resize the browser window executing this method so that its
width and heightare changed by the number of pixels specified by the first and
second,respectively, argument values. These values should be integers.
• print(): Print the document contained in the window executing this method as if the browser’s
Print button had been clicked.
All properties of the global object can be accessed directly:

3.12 DOM (DOCUMENT OBJECT MODEL)


• Document Object Model is an API that represents and interacts with HTML or XML
documents.
• HTML is used to structure the web pages and Javascript is used to add behavior to our web
pages. When an HTML file is loaded into the browser, the javascript can not understand the
HTML document directly.
• In simpler terms, when a browser loads a webpage, it creates a model of that page. This
model is the DOM tree and is filed in the browser’s memory.
• It provides functionality globally to the document, including how to obtain the page details
and create new elements in the document. Remember, DOM is neither a part of HTML
nor JavaScript; it’s a separate set of rules.
• With the HTML DOM, you can use JavaScript to build HTML documents, navigate their
hierarchical structure, and add, modify, or delete elements and attributes or their content,
and so on. Almost anything found in an HTML document can be accessed, changed, deleted,
or added using the JavaScript with the help of HTML DOM.
<html>
<head>
<title>My Page</title>
</head>
<body>
<div id="div">
<h1>Mobile OS</h1>
</div>
<ul>
<li>Android</li>
55
<li>iOS</li>
</ul>
</body>
</html>
The above HTML document can be represented by the following DOM tree:

Every element, attribute, and text content in the HTML creates its own DOM node in the tree. A
DOM tree consists of four main types of nodes:

Document node: This is added at the top of the tree and represents the entire page in the browser. It
is the starting point in the DOM tree; we need to navigate via the document node to access any
other node in your DOM tree.
Element nodes: All the HTML elements like heading tags (<h1> to <h6>) and paragraph tags
(<p>) in the page create an element node in the tree. we use these nodes to gain access to the
elements’ attributes and text nodes.
Attribute nodes: When the opening tags in the HTML document contains attributes, the tree
represents them as attribute nodes. These are not the children of the element nodes but a part of
them.
Text nodes: Once you have access to the element node, you can reach the text content within that
element, stored inside the text nodes of the DOM tree. These nodes cannot have child nodes. Thus,
a text node always creates a new branch in the DOM tree, and no further branches come out of it.

56
So, a corresponding document is created (DOM). DOM is basically the representation of the same
HTML document but in a different format with the use of objects.

Working with the DOM Tree in JavaScript DOM


To access and modify the DOM tree, you need to follow two steps:
· Locate the node representing the element
· Works with the node’s content, child elements, and attributes.
DOM Methods
 HTML DOM methods are actions you can perform (on HTML Elements).
 HTML DOM properties are values (of HTML Elements) that you can set or change.
 In the DOM, all HTML elements are defined as objects.
 The programming interface is the properties and methods of each object.
 A property is a value that you can get or set (like changing the content of an HTML
element).
 A method is an action you can do (like add or deleting an HTML element).
Finding HTML Elements
Method Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class name

Changing HTML Elements


Method Description
element.innerHTML = new html content Change the inner HTML of an element
element.attribute = new value Change the attribute value of an HTML element
element.setAttribute(attribute, value) Change the attribute value of an HTML element
element.style.property = new style Change the style of an HTML element

Adding Events Handlers


Method Description
document.getElementById(id).onclick = Adding event handler code to an onclick event
function(){code}

57
Example1
<html>
<head>
<script type="text/javascript">
function getcube()
{
let number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
</head>
<body>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
</body>
</html>

Example2:
<html>
<head>
<style type="text/css">
h1{
text-align: center;
}
</style>
</head>
<body>
<h1>TO DO LIST</h1>
<ul>
<h2 id='one'> JavaScript Tutorial</h2>
<li>Learning the concepts</li>
<li>Practicing the codes</li>
<li>Taking quizzes</li>
<li>Solving Interview Questions</li>
<script type="text/JavaScript">
document.getElementById('one').style.color="maroon"; //change font color
document.querySelector("h1").style.backgroundColor = "blue"; //change background color
</script>
</ul>
</body> </html>
58
Example-3
Modifying the style of an Element
<html>
<head>
<title></title>
<script type="text/javascript">
function color_change(id)
{
if(id=='r')
document.body.style.backgroundColor="red";
else if(id=='b')
document.body.style.backgroundColor="blue";
else if(id=='g')
document.body.style.backgroundColor="green";
}
</script>
</head>
<body>
<input type="Button" value="Red" id="r" onclick="color_change(id)"/>
<input type="Button" value="Blue" id="b" onclick="color_change(id)"/>
<input type="Button" value="Green" id="g" onclick="color_change(id)"/>
</body>
</html>

59
Methods to Select Multiple Elements (NodeLists)
There are three common ways to select multiple elements in the tree:
• getElementsByClassName(): Selects all the elements that have a specified value for the
class attribute.
• For example – getElementsByClassName(‘mandatory’)
getElementsByTagName(): Selects all the elements that have the specified tag names.
For example – getElementsByTagName(‘h1’)
• querySelectorAll(): Uses a CSS selector, returns all the matching elements.
For example – querySelectorAll(‘li.mandatory’)

<html>
<head>
<style type="text/css">
h1{
text-align: center;
}
</style>
</head>
<body>
<h1>TO DO LIST</h1>
<ul>
<h2 > JavaScript Tutorial</h2>
<li id="one" class="mandatory">Learning the concepts</li>
<li id="two" class="mandatory">Practicing the codes</li>
<li id="three">Taking quizzes</li>
<li id="four">Solving Interview Questions</li>
</ul>

60
<script type="text/JavaScript">
var list_qs = document.querySelectorAll("li.mandatory"); //NodeList
list_qs[0].style.backgroundColor = "blue"; //change background color
var list_cn = document.getElementsByClassName('mandatory'); //NodeList
list_cn[0].style.color="white"; //change font color
var list_tn = document.getElementsByTagName('h1'); //NodeList
list_tn[0].style.color="gray"; //change font color
</script>
</body>
</html>

Get/ update Element Content


For Text only: You can access and update the text in the containing element (and its children) with
the help of two properties:
• textContent
document.getElementById('p').textContent; (accessing)
document.getElementById('p1').textContent = newText; (updating)
• innerText
document.getElementById('p').innerText; (accessing)
document.getElementById('p1').innerText = newText; (updating)

61
• Javascript interprets DOM easily i.e
javascript can not understand the
tags(<h1>H</h1>) in HTML document
but can understand object h1 in DOM.
Now, Javascript can access each of the
objects (h1, p, etc) by using different
functions.
Structure of DOM: DOM can be thought of as
a Tree or Forest(more than one tree). The term structure model is sometimes used to describe the
tree-like representation of a document. Each branch of the tree ends in a node, and each node
contains objects Event listeners can be added to nodes and triggered on an occurrence of a given
event

3.13 ASYNCHRONOUS PROGRAMMING.


Asynchronous Programming:
• Synchronous JavaScript: Every statement of the code gets executed one by one. So,
basically a statement has to wait for the earlier statement to get executed. Every line of code waits
for its previous one to get executed first and then it gets executed. Synchronous operations occur
when JavaScript is single-threaded.
By default, JavaScript is a synchronous, single threaded programming language. This means that
instructions can only run one after another, and not in parallel. That is, the JavaScript engine can
only process one statement at a time in a single thread.
<html>
<head>
<script type="text/javascript">
console.log("one");
console.log("Two");
console.log("Three");
</script>
</head>
<body>
</body>
<html>

62
• Asynchronous JavaScript: When JavaScript is running asynchronously, the instructions
are not necessarily executed one after the other.
In Synchronous Java script we wanted to fetch some large amount of data from a database and then
display it on our interface. When the interpreter reaches the instruction that fetches this data, the rest
of the code is blocked from executing until the data has been fetched and returned. To avoid this we
use Asynchronous JavaScript. Four ways we can implement Asynchronous JavaScript
i) setTimeout
ii) callback
iii) promise
iv) async and await
i) setTimeout: The setTimeout() method executes a block of code after the specified time. The
setTimeout is a JavaScript function that takes two parameters. The first parameter is another
function, and the second is the time after which that function should be executed in milliseconds
Syntax:
setTimeout(function, milliseconds);
Its parameters are:
function - a function containing a block of code
milliseconds - the time after which the function is executed
<html>
<head>
<script type="text/javascript">
function cal(){
console.log("Two");
}
console.log("one");
setTimeout(cal,4000);
console.log("Three");
</script>
</head>
<body>
</body>
<html>

additional argumentscan also be passed to the setTimeout() method.


setTimeout(function, milliseconds, parameter1, ....paramenterN);

63
ii) callback
A callback is a function that is passed inside another function, and then called in that function to
perform a task.
<html>
<head>
<script type="text/javascript">
// function
function greet(name, callback) {
console.log('Hi' + ' ' + name);
callback();
}
// callback function
function callMe() {
console.log('I am callback function');
}
// passing function as an argument
greet('Peter', callMe);
</script>
</head>
<body>
</body>
<html>

The callMe() function is a callback function. The benefit of using a callback function is that you can
wait for the result of a previous function call and then execute another function call.
<html>
<head>
<script type="text/javascript">
function mul()
{
let c=90;
let res=c*c;
console.log("The Result "+res);
}
setTimeout(mul,5000);
console.log("Hai");
</script>
</head>
<body>
</body>
<html>

64
Demo1:
<html>
<head>
<script type="text/javascript">
function add (a,b)
{
c=a+b;
mul(c)
}
function mul(c)
{
let res=c*c;
console.log("The Result "+res);
}
setTimeout(add,5000,2,3);
console.log("Hai");
</script>
</head>
<body>
</body>
<html>

Demo2:
<html>
<head>
<script type="text/javascript">
function add (a,b,m)
{
c=a+b;
m(c)
}
function mul(c)
{
let res=c*c;
console.log("The Result "+res);
}
setTimeout(add,5000,2,3,mul);
console.log("Hai");
</script>
</head>
<body>
</body> <html>
65
iii) promise
A promise is a good way to handle asynchronous operations. It is used to find out if the
asynchronous operation is successfully completed or not.
A promise may have one of three states.
1. Pending
2. Fulfilled
3. Rejected
• A promise starts in a pending state. That means the process is not complete. If the operation
is successful, the process ends in a fulfilled state. And, if an error occurs, the process ends in
a rejected state.
• For example, when you request data from the server by using a promise, it will be in a
pending state. When the data arrives successfully, it will be in a fulfilled state. If an error
occurs, then it will be in a rejected
state.
• . It produces a value when the async
operation completes successfully or
produces an error if it doesn't
complete.
• "Producing code" is code that can
take some time
• "Consuming code" is code that must wait for the result
• A Promise is a JavaScript object that links producing code and consuming code

let promise = new Promise(function(resolve, reject) {


resolve(); // when successful
reject(); // when error } );
The Promise() constructor takes a function as an argument. The function also accepts two functions
resolve() and reject()
If the promise returns successfully, the resolve() function is called. And, if an error occurs, the
reject() function is called.

66
Demo:
<html>
<head>
<script type="text/javascript">
let a=5;
let proobj = new Promise(function (resolve, reject)
{
if(a==5)
resolve("Sucess");
else
reject("Error");
});
console.log(proobj);
</script>
</head>
<body>
</body>
</html>

Demo2:
<html>
<head>
<script type="text/javascript">
let a=6;
let proobj = new Promise(function (resolve, reject)
{
if(a==5)
resolve("Sucess");
else
reject("Error");
});
proobj.then( function(val){console.log(val)},function(val1){console.log(val1)});
</script>
</head>
<body>
</body>
</html>

67
iv) async and await
• async keyword with a function to represent that the function is an asynchronous function.
The async function returns a promise.
• The syntax of async function is:
async function name(parameter1, parameter2, ...paramaterN) {
// statements
}
The await keyword is used inside the async function to wait for the asynchronous operation. The
async function allows the asynchronous method to be executed in a seemingly synchronous way

<html>
<head>
<script type="text/javascript">
let promise = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('Promise resolved')}, 4000);
});
// async function
async function asyncFunc() {
// wait until the promise resolves
let result = await promise;
console.log(result);
console.log('hello');
}
// calling the async function
asyncFunc();
</script>
</head>
<body>
</body> </html>

68
Errors are can handled using try/catch block. For example,
catch() is invoked when a promise is either rejected or some error has occurred in execution. It is
used as an Error Handler whenever at any step there is a chance of getting an error.
Parameters:
catch() method takes one function as parameter.
1. Function to handle errors or promise rejections.(.catch() method internally calls .then(null,
errorHandler), i.e. .catch() is just a shorthand for .then(null, errorHandler) )
Syntax:
.catch(function(error){
//handle error
})
Sample Program2:
<html>
<head>
<script type="text/javascript">
let a=6;
let proobj = new Promise(function (resolve, reject)
{
if(a==5)
resolve("Sucess");
else
reject("Error");
});
// async function
async function asyncFunc() {
try {
// wait until the promise resolves
let result = await proobj ;
console.log(result);
}
catch(error)
{
console.log(error);
}
}
// calling the async function
asyncFunc(); // Promise resolved
</script>
</head> <body> </body> </html>

69
Benefits of Using async Function
The code is more readable than using a callback or a promise.
Error handling is simpler.
Debugging is easier.

70

You might also like