Unit III
Unit III
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.
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>
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.
• 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>
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
};
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)
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>
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>
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.
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>
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>
• 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>
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>
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>
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>
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>
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>
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>
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
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>
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)
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
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.
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.
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>
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)
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:
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.
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>
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
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>
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
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