Javascript
Javascript
Although, JavaScript has no connectivity with Java programming language. The name was
suggested and provided in the times when Java was gaining popularity in the market. In
addition to web browsers, databases such as CouchDB and MongoDB uses JavaScript as their
scripting and query language.
Features of JavaScript
There are following features of JavaScript:
1. All popular web browsers support JavaScript as they provide built-in execution
environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it is
a structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast
(depending on the operation).
4. JavaScript is an object-oriented programming language that uses prototypes rather
than using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows, macOS, etc.
8. It provides good control to the users over the web browsers.
Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:
o Client-side validation,
1
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm
dialog box and prompt dialog box),
o Displaying clocks etc.
<html>
<body>
<h2>Weline to JavaScript</h2>
<script>
</script>
</body>
</html>
JavaScript Example
Javascript example is easy to code. JavaScript provides 3 places to put the JavaScript
code: within body tag, within head tag and external JavaScript file.
<html>
<body>
<script type="text/javascript">
</script>
</body>
</html>
2
The text/javascript is the content type that provides information to the browser
about the data.
<html>
<body>
<script type="text/javascript">
alert("Hello Digitinstitute");
</script>
</body>
</html>
In this example, we are creating a function msg(). To create function in JavaScript, you
need to write function with function_name as given below.
To call function, you need to work on event. Here we are using onclick event to call
msg() function
3
<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello Digitinstitute");
}
</script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
It provides code re usability because single JavaScript file can be used in several html
pages.
Let's create an external JavaScript file that prints Hello Digitinstitute in a alert dialog
box
message.js
1. function msg(){
2. alert("Hello Digitinstitute");
3. }
Let's include the JavaScript file into html page. It calls the JavaScript function on
button click.
index.html
4
<html>
<head>
<script type="text/javascript" src="message.js"></script>
</head>
<body>
<p>Weline to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
JavaScript comment
1.
The JavaScript comments are meaningful way to deliver message. It is used to add
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.
5
Advantages of JavaScript comments
1. Single-line comment
2. Multi-line comment
Let’s see the example of single-line comment i.e. added before the statement.
<html>
<body>
<script>
document.write("hello javascript");
</script>
</body>
</html>
Let’s see the example of single-line comment i.e. added after the statement.
6
<html>
<body>
<script>
var a=10;
var b=20;
</script>
</body>
</html>
It is represented by forward slash with asterisk then asterisk with forward slash. For
example:
<html>
<body>
<script>
</script>
</body>
</html>
JavaScript Variable
A JavaScript variable is simply a name of storage location. There are two types of
variables in JavaScript : local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers).
7
1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.
1. var x = 10;
2. var _value="sonoo";
1. var 123=30;
2. var *aa=320;
<html>
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>
8
JavaScript local variable
A JavaScript local variable is declared inside block or function. It is accessible within
the function or block only. For example:
1. <script>
2. function abc(){
3. var x=10;//local variable
4. }
5. </script>
Or,
1. <script>
2. If(10<13){
3. var y=20;//JavaScript local variable
4. }
5. </script>
<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
9
b();
</script>
<html>
<body>
<script>
function a(){
alert(value);
function b(){
alert(value);
a();
</script>
</body>
</html>
1. window.value=90;
Now it can be declared inside any function and can be accessed from any function. For
exampl
10
<html>
<body>
<script>
function m(){
function n(){
m();
n();
</script>
</body>
</html>
1. var value=50;
2. function a(){
3. alert(window.value);//accessing global variable
4. }
11
JavaScript is a dynamic type language, means you don't need to specify type of the
variable because it is dynamically used by JavaScript engine. You need to use var here
to specify the data type. It can hold any type of values such as numbers, strings etc.
For example:
12
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands.
For example
1. var sum=10+20;
1. Arithmetic Operators
2. comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
/ Division 20/10 = 2
13
JavaScript comparison Operators
The JavaScript comparison operator compares the two operands. The comparison
operators are as follows:
14
~ Bitwise NOT (~10) = -10
= Assign 10+10 = 20
15
/= Divide and assign var a=10; a/=2; Now a = 5
Operator Description
(?:) Conditional Operator returns value based on the condition. It is like if-else.
JavaScript If-else
The JavaScript if-else statement is used to execute the code whether condition is true
or false. There are three forms of if statement in JavaScript.
1. If Statement
2. If else statement
3. if else if statement
16
JavaScript If statement
It evaluates the content only if expression is true. The signature of JavaScript if
statement is given below.
1. if(expression){
2. //content to be evaluated
3. }
<html>
<body>
<script>
var a=20;
if(a>10){
</script>
</body>
</html>
1. if(expression){
2. //content to be evaluated if condition is true
3. }
4. else{
5. //content to be evaluated if condition is false
6. }
17
<html>
<body>
<script>
var a=20;
if(a%2==0){
else{
</script>
</body>
</html>
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}
18
<html>
<body>
<script>
var a=20;
if(a==10){
else if(a==15){
else if(a==20){
else{
</script>
</body>
</html>
JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple
expressions. It is just like else if statement that we have learned in previous page. But
it is convenient than if..else..if because it can be used with numbers, characters etc.
switch(expression){
case value1:
code to be executed;
break;
case value2:
19
code to be executed;
break;
......
default:
code to be executed if above values are not matched;
}
<html>
<body>
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
document.write(result);
</script>
</body>
</html>
20
JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while or
for-in loops. It makes the code inpact. It is mostly used in array.
1. for loop
2. while loop
3. do-while loop
<!DOCTYPE html>
<html>
<body>
<script>
document.write(i + "<br/>")
</script>
</body>
</html>
21
2) JavaScript while loop
The JavaScript while loop iterates the elements for the infinite number of times. It
should be used if number of iteration is not known. The syntax of while loop is given
below.
1. while (condition)
2. {
3. code to be executed
4. }
<html>
<body>
<script>
var i=11;
while (i<=15)
document.write(i + "<br/>");
i++;
</script>
</body>
</html>
1. do{
2. code to be executed
3. }while (condition);
22
<html>
<body>
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
</body>
</html>
JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function
many times to reuse the code.
23
JavaScript Function Example
Let’s see the simple example of function in JavaScript that does not has arguments.
<html>
<body>
<script>
function msg(){
</script>
</body>
</html>
<html>
<body>
<script>
function getcube(number){
alert(number*number*number);
</script>
<form>
</form>
</body>
</html>
24
Function with Return Value
We can call function that returns a value and use it in our program. Let’s see the
example of function that returns value.
<html>
<body>
<script>
function getInfo(){
</script>
<script>
document.write(getInfo());
</script>
</body>
</html>
Method Description
apply() It is used to call a function contains this value and a single array of arguments.
call() It is used to call a function contains this value and an argument list.
25
JavaScript Function Object Examples
<html>
<body>
<script>
document.writeln(add(2,5));
</script>
</body>
</html>
Example 2
<html>
<body>
<script>
document.writeln(pow(2,3));
</script>
</body>
</html>
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method). For
example: car, pen, bike, chair, glass, keyboard, monitor etc.
26
JavaScript is template based not class based. Here, we don't create class to get the
object. But, we direct create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
1. object={property1:value1,property2:value2.....propertyN:valueN}
<html>
<body>
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
</script>
</body>
</html>
27
1. var objectname=new Object();
<html>
<body>
<script>
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
</script>
</body>
</html>
<html>
<body>
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
28
document.write(e.id+" "+e.name+" "+e.salary);
</script>
</body>
</html>
<html>
<body>
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
this.changeSalary=changeSalary;
function changeSalary(otherSalary){
this.salary=otherSalary;
e.changeSalary(45000);
</script>
</body>
</html>
29
JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
var arrayname=[value1,value2.....valueN];
<html>
<body>
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
</script>
</body>
</html>
<html>
<body>
30
<script>
var i;
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
</script>
</body>
</html>
<html>
<body>
<script>
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
</script>
</body>
</html>
31
JavaScript String
The JavaScript string is an object that represents a sequence of characters.
1. By string literal
2. By string object (using new keyword)
1) By string literal
The string literal is created using double quotes. The syntax of creating string using
string literal is given below:
<html>
<body>
<script>
document.write(str);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
32
var stringname=new String("hello javascript string");
document.write(stringname);
</script>
</body>
</html>
Methods Description
charCodeAt() It provides the Unicode value of a character present at the specified index.
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.
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.
33
slice() It is used to fetch the part of the given string. It allows us to assign positive as well negative
index.
toLocaleLowerCase() It converts the given string into lowercase letter on the basis of host?s current locale.
toLocaleUpperCase() It converts the given string into uppercase letter on the basis of host?s current locale.
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.
<html>
<body>
<script>
var str="javascript";
document.write(str.charAt(2));
</script>
</body>
</html>
34
<html>
<body>
<script>
var s3=s1+s2;
document.write(s3);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
var n=s1.indexOf("from");
document.write(n);
</script>
</body>
</html>
<html>
<body>
35
<script>
var s2=s1.toLowerCase();
document.write(s2);
</script>
</body>
</html>
<html>
<body>
<script>
var s2=s1.toUpperCase();
document.write(s2);
</script>
</body>
</html>
<html>
<body>
<script>
var s1="abcdefgh";
var s2=s1.slice(2,5);
36
document.write(s2);
</script>
</body>
</html>
<html>
<body>
<script>
var s2=s1.trim();
document.write(s2);
</script>
</body>
</html>
1. <script>
2. var str="This is Digitinstitute website";
3. document.write(str.split(" ")); //splits the given string.
4. </script>
You can use different Date constructors to create date object. It provides methods to
get and set day, month, year, hour, minute and seconds.
Constructor
37
You can use 4 variant of Date constructor to create date object.
1. Date()
2. Date(milliseconds)
3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)
Methods Description
getDate() It returns the integer value between 1 and 31 that represents the day for the specified date
on the basis of local time.
getDay() It returns the integer value between 0 and 6 that represents the day of the week on the basis
of local time.
getFullYears() It returns the integer value that represents the year on the basis of local time.
getHours() It returns the integer value between 0 and 23 that represents the hours on the basis of local
time.
getMilliseconds() It returns the integer value between 0 and 999 that represents the milliseconds on the basis
of local time.
getMinutes() It returns the integer value between 0 and 59 that represents the minutes on the basis of local
time.
getMonth() It returns the integer value between 0 and 11 that represents the month on the basis of local
time.
getSeconds() It returns the integer value between 0 and 60 that represents the seconds on the basis of local
time.
setDate() It sets the day value for the specified date on the basis of local time.
38
setDay() It sets the particular day of the week on the basis of local time.
setFullYears() It sets the year value for the specified date on the basis of local time.
setHours() It sets the hour value for the specified date on the basis of local time.
<html>
<body>
<script>
document.getElementById('txt').innerHTML=today;
</script>
</body>
</html>
<html>
<body>
<script>
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
39
</script>
</body>
</html>
There are two ways to set interval in JavaScript: by setTimeout() or setInterval() method.
<html>
<body>
<script>
window.onload=function(){getTime();}
function getTime(){
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
setTimeout(function(){getTime()},1000);
//setInterval("getTime()",1000);//another way
function checkTime(i){
if (i<10){
i="0" + i;
return i;
40
}
</script>
</body>
</html>
JavaScript Math
The JavaScript math object provides several constants and methods to perform
mathematical operation. Unlike date object, it doesn't have constructors.
Methods Description
ceil() It returns a smallest integer value, greater than or equal to the given number.
floor() It returns largest integer value, lower than or equal to the given number.
41
hypot() It returns square root of sum of the squares of given numbers.
Math.sqrt(n)
The JavaScript math.sqrt(n) method returns the square root of the given number.
<html>
<body>
<script>
document.getElementById('p1').innerHTML=Math.sqrt(17);
</script>
</body>
42
</html>
Math.random()
The JavaScript math.random() method returns the random number between 0 to 1.
<html>
<body>
<script>
document.getElementById('p2').innerHTML=Math.random();
</script>
</body>
</html>
Math.pow(m,n)
The JavaScript math.pow(m,n) method returns the m to the power of n that is mn.
<html>
<body>
<script>
document.getElementById('p3').innerHTML=Math.pow(3,4);
</script>
</body>
</html>
Math.floor(n)
The JavaScript math.floor(n) method returns the lowest integer for the given number.
For example 3 for 3.7, 5 for 5.9 etc.
43
<html>
<body>
<script>
document.getElementById('p4').innerHTML=Math.floor(4.6);
</script>
</body>
</html>
Math.ceil(n)
The JavaScript math.ceil(n) method returns the largest integer for the given number.
For example 4 for 3.7, 6 for 5.9 etc.
<html>
<body>
<script>
document.getElementById('p5').innerHTML=Math.ceil(4.6);
</script>
</body>
</html>
Math.round(n)
The JavaScript math.round(n) method returns the rounded integer nearest for the
given number. If fractional part is equal or greater than 0.5, it goes to upper value 1
otherwise lower value 0. For example 4 for 3.7, 3 for 3.3, 6 for 5.9 etc.
44
<html>
<body>
<script>
document.getElementById('p6').innerHTML=Math.round(4.3);
document.getElementById('p7').innerHTML=Math.round(4.7);
</script>
</body>
</html>
By the help of Number() constructor, you can create number object in JavaScript. For
example:
<html>
<body>
<script>
45
document.write(x+" "+y+" "+z+" "+n);
</script>
</body>
</html>
Constant Description
Methods Description
46
toExponential() It returns the string that represents exponential notation of the given number.
toFixed() It returns the string that represents a number with exact digits after a decimal point.
JavaScript Boolean
JavaScript Boolean is an object that represents value in two states: true or false. You
can create the JavaScript Boolean object by Boolean() constructor as given below.
1. <script>
2. document.write(10<20);//true
3. document.write(10<5);//false
4. </script>
Property Description
constructor returns the reference of Boolean function that created Boolean object.
47
prototype enables you to add properties and methods in Boolean prototype.
Method Description
The default object of browser is window means you can call all the functions of window
by specifying window or directly. For example:
1. window.alert("hello Digitinstitute");
is same as:
1. alert("hello Digitinstitute");
You can use a lot of properties (other objects) defined underneath the window object like
document, history, screen, navigator, location, innerHeight, innerWidth,
48
Window Object
Window is the object of browser, it is not the object of javascript. The javascript
objects are string, array, date etc.
Method Description
confirm() displays the confirm dialog box containing message with ok and cancel button.
setTimeout() performs action after specified time like calling function, evaluating expressions etc.
1. <script type="text/javascript">
2. function msg(){
3. alert("Hello Alert Box");
4. }
5. </script>
6. <input type="button" value="click" onclick="msg()"/>
49
Example of confirm() in javascript
It displays the confirm dialog box. It has message with ok and cancel buttons.
1. <script type="text/javascript">
2. function msg(){
3. var v= confirm("Are u sure?");
4. if(v==true){
5. alert("ok");
6. }
7. else{
8. alert("cancel");
9. }
10.
11. }
12. </script>
13.
14. <input type="button" value="delete record" onclick="msg()"/>
It displays prompt dialog box for input. It has message and textfield.
1. <script type="text/javascript">
2. function msg(){
3. var v= prompt("Who are you?");
4. alert("I am "+v);
5.
6. }
7. </script>
50
8. <input type="button" value="click" onclick="msg()"/>
1. <script type="text/javascript">
2. function msg(){
3. open("http://www.Digitinstitute.in");
4. }
5. </script>
6. <input type="button" value="Digitinstitute" onclick="msg()"/>
1. <script type="text/javascript">
2. function msg(){
3. setTimeout(
4. function(){
5. alert("Weline to Digitinstitute after 2 seconds")
6. },2000);
7.
8. }
9. </script>
10.
11. <input type="button" value="click" onclick="msg()"/>
51
JavaScript History Object
The JavaScript history object represents an array of URLs visited by the user. By using
this object, you can load previous, forward or any particular page.
1. window.history
Or,
1. history
52
Example of history object
Let’s see the different usage of history object.
window.navigator
Or,
navigator
53
7 userLanguage returns the user language. It is supported in IE only.
<html>
<body>
<script>
document.writeln("<br/>navigator.appCodeName: "+navigator.appCodeName);
document.writeln("<br/>navigator.appName: "+navigator.appName);
document.writeln("<br/>navigator.appVersion: "+navigator.appVersion);
document.writeln("<br/>navigator.cookieEnabled: "+navigator.cookieEnabled);
document.writeln("<br/>navigator.language: "+navigator.language);
document.writeln("<br/>navigator.userAgent: "+navigator.userAgent);
document.writeln("<br/>navigator.platform: "+navigator.platform);
document.writeln("<br/>navigator.onLine: "+navigator.onLine);
</script>
</body>
</html>
54
JavaScript Screen Object
The JavaScript screen object holds information of browser screen. It can be used to
display screen width, height, colorDepth, pixelDepth etc.
window.screen
Or,
screen
<html>
<body>
<script>
document.writeln("<br/>screen.width: "+screen.width);
document.writeln("<br/>screen.height: "+screen.height);
document.writeln("<br/>screen.availWidth: "+screen.availWidth);
document.writeln("<br/>screen.availHeight: "+screen.availHeight);
55
document.writeln("<br/>screen.colorDepth: "+screen.colorDepth);
document.writeln("<br/>screen.pixelDepth: "+screen.pixelDepth);
</script>
</body>
</html>
window.document
or
document
56
Methods of document object
We can access and change the contents of document by its methods.
Method Description
writeln("string") writes the given string on the doucment with newline character at the end.
getElementsByName() returns all the elements having the given name value.
getElementsByTagName() returns all the elements having the given tag name.
57
getElementsByClassName() returns all the elements having the given class name.
Here, document is the root element that represents the html document.
value is the property, that returns the value of the input text.
value is the property, that returns the value of the input text.
Let's see the simple example of document object that prints name with weline
message.
<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>
58
Javascript - document.getElementById()
method
The document.getElementById() method returns the element of specified id.
Let's see the simple example of document.getElementById() method that prints cube
of the given number.
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
Javascript -
document.getElementsByName() method
The document.getElementsByName() method returns all the element of specified
name.
1. document.getElementsByName("name")
59
Example of document.getElementsByName() method
In this example, we going to count total number of genders. Here, we are using
getElementsByName() method to get all the genders.
<script type="text/javascript">
function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">
Javascript -
document.getElementsByTagName()
method
The document.getElementsByTagName() method returns all the element of
specified tag name.
1. document.getElementsByTagName("name")
60
Example of document.getElementsByTagName() method
In this example, we going to count total number of paragraphs used in the document.
To do this, we have called the document.getElementsByTagName("p") method that
returns the total paragraphs.
<script type="text/javascript">
function countpara(){
var totalpara=document.getElementsByTagName("p");
alert("total p tags are: "+totalpara.length);
}
</script>
<p>This is a pragraph</p>
<p>Here we are going to count total number of paragraphs by getElementByTagName() method.</p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button>
In this example, we going to count total number of h2 and h3 tags used in the
document.
<script type="text/javascript">
function counth2(){
var totalh2=document.getElementsByTagName("h2");
alert("total h2 tags are: "+totalh2.length);
}
function counth3(){
var totalh3=document.getElementsByTagName("h3");
alert("total h3 tags are: "+totalh3.length);
}
</script>
61
<h2>This is h2 tag</h2>
<h2>This is h2 tag</h2>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<button onclick="counth2()">count h2</button>
<button onclick="counth3()">count h3</button>
Javascript - innerHTML
The innerHTML property can be used to write the dynamic html on the html
document.
It is used mostly in the web pages to generate the dynamic html such as registration
form, inment form, links etc.
In this example, we are dynamically writing the html form inside the div name having
the id mylocation. We are identifing this position by calling the
document.getElementById() method.
<html>
<body>
function showcommentform() {
document.getElementById('mylocation').innerHTML=data;
62
</script>
<form name="myForm">
<div id="mylocation"></div>
</form>
</body>
</html>
<html>
<head>
<title>First JS</title>
<script>
var flag=true;
function commentform(){
var cform="<form action='comment'>Enter Name:<br><input type='text' name='nam
e'/><br/>
Enter Email:<br><input type='email' name='email'/><br>Enter comment:<br/>
<textarea rows='5' cols='70'></textarea><br>
<input type='submit' value='Post comment'/></form>";
if(flag){
document.getElementById("mylocation").innerHTML=cform;
flag=false;
}else{
document.getElementById("mylocation").innerHTML="";
flag=true;
}
}
</script>
</head>
<body>
<button onclick="commentform()">comment</button>
<div id="mylocation"></div>
63
</body>
</html>
Javascript - innerText
The innerText property can be used to write the dynamic text on the html document.
Here, text will not be interpreted as html text but a normal text.
It is used mostly in the web pages to generate the dynamic content such as writing the
validation message, password strength etc.
<html>
<body>
function validate() {
var msg;
if(document.myForm.userPass.value.length>5){
msg="good";
else{
msg="poor";
document.getElementById('mylocation').innerText=msg;
</script>
<form name="myForm">
</form>
64
</body>
</html>
DropDownList Example
<html>
<head>
</head>
<script>
function location()
var a = document.getElementById("myList");
document.getElementById("loc").value = a.options[mylist.selectedIndex].text;
</script>
<body>
<form>
<b> Select you favourite tutorial site using dropdown list </b>
<option> chennai</option>
<option> Banglore</option>
</select>
</form>
65
</body>
</html>
<html>
<body>
<script>
function checkCheckbox() {
var yes = document.getElementById("myCheck1");
var no = document.getElementById("myCheck2");
if (yes.checked == true && no.checked == true){
return document.getElementById("error").innerHTML = "Please mark only one c
heckbox either Yes or No";
}
else if (yes.checked == true){
var y = document.getElementById("myCheck1").value;
66
return document.getElementById("result").innerHTML = y;
}
else if (no.checked == true){
var n = document.getElementById("myCheck2").value;
return document.getElementById("result").innerHTML = n;
}
else {
return document.getElementById("error").innerHTML = "*Please mark any of ch
eckbox";
}
}
</script>
</body>
Radio button:
A radio button is an icon that is used in forms to take input from the user. It allows the
users to choose one value from the group of radio buttons. Radio buttons are basically
used for the single selection from multiple ones, which is mostly used in GUI forms.
You can mark/check only one radio button between two or more radio buttons. In this
chapter, we will guide you on how to check a radio button using the JavaScript
programming language
using HTML, and then we will use JavaScript programming to check the radio button. We
will also check which radio button value is selected.
<html>
<body>
67
<input type="radio" name="JTP" id="winter" value="winter">Winter<br>
</body>
</html>
However, we have to write the JavaScript code to get the value of the checked radio
button, which we will see in the chapter below:
1. getElementById
2. querySelector
o The input radio checked property is used to check whether the checkbox is selected or
not. Use document.getElementById('id').checked method for this. It will return
the checked status of the radio button as a Boolean value. It can be either true or false.
o True - If radio button is selected.
o False - If radio button is not selected/ checked.
o See the JavaScript code below to know how it works:
if(document.getElementById('summer').checked == true) {
document.write("Summer radio button is selected");
68
} else {
document.write("Summer radio button is not selected");
}
querySelector()
The querySelector() function is a DOM method of JavaScript. It uses the common name
property of radio buttons inside it. This method is used as given below to check which
radio button is selected.
Example
For example, we have a radio button named Summer and id = 'summer'. Now, we will
check using this button id that the radio button is marked or not.
document.querySelector('input[name="JTP"]:checked')
Example
For example, we have a group of radio buttons having the name property name =
'season' for all buttons. Now, between these buttons named season we will check
which one is selected.
Using getElementById ()
69
if(document.getElementById('summer').checked) {
var selectedValue = document.getElementById('summer').value;
alert("Selected Radio Button is: " + selectedValue);
}
Using querySelector()
Following is the code to get the value of checked radio button using querySelector()
method:
<html>
<body>
</body>
<script>
function checkButton() {
if(document.getElementById('summer').checked) {
70
document.getElementById("disp").innerHTML
= document.getElementById("summer").value
else if(document.getElementById('winter').checked) {
document.getElementById("disp").innerHTML
= document.getElementById("winter").value
else if(document.getElementById('rainy').checked) {
document.getElementById("disp").innerHTML
= document.getElementById("rainy").value
else if(document.getElementById('autumn').checked) {
document.getElementById("disp").innerHTML
= document.getElementById("autumn").value
else {
document.getElementById("error").innerHTML
</script>
</html>
71
JavaScript Form Validation
It is important to validate the form submitted by the user because it can have
inappropriate values. So, validation is must to authenticate user.
JavaScript provides facility to validate the form on the client-side so data processing
will be faster than server-side validation. Most of the web developers prefer JavaScript
form validation.
Through JavaScript, we can validate name, password, email, date, mobile numbers and
more fields.
Here, we are validating the form on form submit. The user will not be forwarded to the next
page until given values are correct.
<html>
<body>
<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
return false;
}else if(password.length<6){
return false;
72
</script>
<body>
</form>
</body>
</html>
<head>
<script type="text/javascript">
function matchpass(){
var firstpassword=document.f1.password.value;
var secondpassword=document.f1.password2.value;
if(firstpassword==secondpassword){
return true;
else{
return false;
</script>
</head>
<body>
73
<form name="f1" >
<input type="submit">
</form>
</body>
</html>
There are many criteria that need to be follow to validate the email id such as:
<html>
<body>
<script>
function validateemail()
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
return false;
74
}
</script>
<body>
</form>
</body>
</html>
JavaScript Classes
In JavaScript, classes are the special type of functions. We can define the class just like
function declarations and function expressions.
The JavaScript class contains various class members within a body including methods
or constructor. The class is executed in strict mode. So, the code containing the silent
error or mistake throws an error.
o Class declarations
o Class expressions
Class Declarations
A class can be defined by using a class declaration. A class keyword is used to declare
a class with any particular name. According to JavaScript naming conventions, the
name of the class always starts with an uppercase letter.
15.8M
317
History of Java
<html>
75
<body>
<script>
//Declaring class
class Employee
//Initializing an object
constructor(id,name)
this.id=id;
this.name=name;
//Declaring method
detail()
document.writeln(this.id+" "+this.name+"<br>")
e2.detail();
</script>
</body>
</html>
76
Let's see an example.
<html>
<body>
<script>
e2.detail();
//Declaring class
class Employee
//Initializing an object
constructor(id,name)
this.id=id;
this.name=name;
detail()
document.writeln(this.id+" "+this.name+"<br>")
</script>
</body>
</html>
77
Class expressions
Another way to define a class is by using a class expression. Here, it is not mandatory
to assign the name of the class. So, the class expression can be named or unnamed.
The class expression allows us to fetch the class name. However, this will not be
possible with class declaration.
<html>
<body>
<script>
constructor(id, name) {
this.id = id;
this.name = name;
};
document.writeln(emp.name);
</script>
</body>
</html>
<html>
<body>
78
<script>
//Declaring class
var emp=class
//Initializing an object
constructor(id,name)
this.id=id;
this.name=name;
//Declaring method
detail()
document.writeln(this.id+" "+this.name+"<br>")
e2.detail();
//Re-declaring class
var emp=class
//Initializing an object
constructor(id,name)
this.id=id;
this.name=name;
79
}
detail()
document.writeln(this.id+" "+this.name+"<br>")
e2.detail();
</script>
</body>
</html>
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method). For
example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is template based not class based. Here, we don't create class to get the
object. But, we direct create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
80
1) JavaScript Object by object literal
The syntax of creating object using object literal is given below:
1. object={property1:value1,property2:value2.....propertyN:valueN
<html>
<body>
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
</script>
</body>
</html>
<body>
<script>
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
</script>
81
</body>
</html>
<html>
<body>
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
</script>
</body>
</html>
<html>
82
<body>
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
this.changeSalary=changeSalary;
function changeSalary(otherSalary){
this.salary=otherSalary;
e.changeSalary(45000);
</script>
</body>
</html>
Points to remember
o The constructor keyword is used to declare a constructor method.
o The class can contain one constructor method only.
o JavaScript allows us to use parent class constructor through super keyword.
83
<html>
<body>
<script>
class Employee {
constructor() {
this.id=101;
document.writeln(emp.id+" "+emp.name);
</script>
</body>
</html>
<html>
<body>
<script>
class InpanyName
constructor()
this.inpany="Digitinstitute";
84
class Employee extends InpanyName {
constructor(id,name) {
super();
this.id=id;
this.name=name;
</script>
</body>
</html>
Points to remember
o The static keyword is used to declare a static method.
o The static method can be of any name.
o A class can contain more than one static method.
o If we declare more than one static method with a similar name, the JavaScript always
invokes the last one.
o The static method can be used to create utility functions.
o We can use this keyword to call a static method within another static method.
o We cannot use this keyword directly to call a static method within the non-static
method. In such case, we can call the static method either using the class name or as
the property of the constructor.
<html>
<body>
85
<script>
class Test
static display()
document.writeln(Test.display());
</script>
</body>
</html>
Example 2
Le's see an example to invoke more than one static method.
<html>
<body>
<script>
class Test
static display1()
static display2()
86
{
document.writeln(Test.display1()+"<br>");
document.writeln(Test.display2());
</script>
</body>
</html>
Example 3
Let's see an example to invoke a static method within the constructor.
<html>
<body>
<script>
class Test {
constructor() {
document.writeln(Test.display()+"<br>");
document.writeln(this.constructor.display());
static display() {
</script>
87
</body>
</html>
JavaScript Encapsulation
The JavaScript Encapsulation is a process of binding the data (i.e. variables) with the
functions acting on that data. It allows us to control the data and validate it. To achieve
an encapsulation in JavaScript: -
Read/Write - Here, we use setter methods to write the data and getter methods read
that data.
<script>
class Student
{
constructor()
{
var name;
var marks;
}
getName()
{
return this.name;
}
setName(name)
88
{
this.name=name;
}
getMarks()
{
return this.marks;
}
setMarks(marks)
{
this.marks=marks;
}
}
var stud=new Student();
stud.setName("John");
stud.setMarks(80);
document.writeln(stud.getName()+" "+stud.getMarks());
</script>
JavaScript Inheritance
The JavaScript inheritance is a mechanism that allows us to create new classes on the
basis of already existing classes. It provides flexibility to the child class to reuse the
methods and variables of a parent class.
The JavaScript extends keyword is used to create a child class on the basis of a parent
class. It facilitates child class to acquire all the properties and behavior of its parent
class.
Points to remember
o It maintains an IS-A relationship.
o The extends keyword is used in class expressions or class declarations.
o Using extends keyword, we can acquire all the properties and behavior of the inbuilt
object as well as custom classes.
o We can also use a prototype-based approach to achieve inheritance.
89
JavaScript extends Example: inbuilt object
<html>
<body>
<script>
constructor() {
super();
}}
document.writeln("Current date:")
document.writeln(m.getDate()+"-"+(m.getMonth()+1)+"-"+m.getFullYear());
</script>
</body>
</html>
<html>
<body>
<script>
constructor(year) {
super(year);
}}
document.writeln("Year value:")
document.writeln(m.getFullYear());
</script>
90
</body>
</html>
<html>
<body>
<script>
class Bike
constructor()
this.inpany="Honda";
constructor(name,price) {
super();
this.name=name;
this.price=price;
</script>
</body>
91
</html>
JavaScript Polymorphism
The polymorphism is a core concept of an object-oriented paradigm that provides a
way to perform a single action in different forms. It provides an ability to call the same
method on different JavaScript objects. As JavaScript is not a type-safe language, we
can pass any type of data members with the methods.
<html>
<body>
<script>
class A
display()
document.writeln("A is invoked");
class B extends A
b.display();
</script>
</body>
</html>
Example 2
Let's see an example where a child and parent class contains the same method. Here,
the object of child class invokes both classes method.
<html>
92
<body>
<script>
class A
display()
document.writeln("A is invoked<br>");
class B extends A
display()
document.writeln("B is invoked");
a.forEach(function(msg)
msg.display();
});
</script>
</body>
</html>
JavaScript Abstraction
An abstraction is a way of hiding the implementation details and showing only the
functionality to the users. In other words, it ignores the irrelevant details and shows
only the required one.
93
Points to remember
o We cannot create an instance of Abstract Class.
o It reduces the duplication of code.
<html>
<body>
<script>
function Vehicle()
this.vehicleName="vehicleName";
Vehicle.prototype.display=function()
function Bike(vehicleName)
this.vehicleName=vehicleName;
Bike.prototype=Object.create(Vehicle.prototype);
document.writeln(bike.display());
94
</script>
</body>
</html>
JavaScript Events
The change in the state of an object is known as an Event. 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, js react
over these events and allow the execution. This process of reacting over the events
is called Event Handling. Thus, js handles the HTML events via Event
Handlers.
For example, when a user clicks over the browser, add js code, which will execute the
task to be performed on the event.
Mouse events:
mouseover onmouseover When the cursor of the mouse moves over the element
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
Keyboard events:
Keydown & Keyup onkeydown & onkeyup When the user press and then release the key
95
Form events:
change onchange When the user modifies or changes the value of a form element
Click Event
<html>
<body>
<!--
function clickevent()
document.write("This is Digitinstitute");
//-->
</script>
<form>
</form>
</body>
</html>
96
MouseOver Event
<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function mouseoverevent()
{
alert("This is Digitinstitute");
}
//-->
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>
Focus Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
<!--
function focusevent()
{
document.getElementById("input1").style.background=" aqua";
}
//-->
</script>
</body>
</html>
97
Keydown Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
//-->
</script>
</body>
</html>
Load event
<html>
<head>Javascript Events</head>
</br>
<body onload="window.alert('Page successfully loaded');">
<script>
<!--
document.write("The page is loaded successfully");
//-->
</script>
</body>
</html>
98
JavaScript onclick event
The onclick event generally occurs when the user clicks on an element. It allows the
programmer to execute a JavaScript's function when an element gets clicked. This
event can be used for validating a form, warning messages and many more.
Using JavaScript, this event can be dynamically added to any element. It supports all
HTML elements except <html>
In HTML
attribute and assigning a JavaScript's function to it. When the user clicks the given button, the
corresponding function will get executed, and an alert dialog box will be displayed on the scree
<html>
<head>
<script>
function fun() {
alert("Welcome to the Digitinstitute.in");
}
</script>
</head>
99
<body>
<h3> This is an example of using onclick attribute in HTML. </h3>
<p> Click the following button to see the effect. </p>
<button onclick = "fun()">Click me</button>
</body>
</html>
element, the corresponding function will get executed, and the text of the paragraph gets changed.
On clicking the <p> element, the background color
, size, border, and color of the text will also get change.
<html>
<head>
<title> onclick event </title>
</head>
<body>
<h3> This is an example of using onclick event. </h3>
<p> Click the following text to see the effect. </p>
<p id = "para">Click me</p>
<script>
document.getElementById("para").onclick = function() {
fun()
};
function fun() {
document.getElementById("para").innerHTML = "Welcome to the Digitinstitute.in";
document.getElementById("para").style.color = "blue";
document.getElementById("para").style.backgroundColor = "yellow";
document.getElementById("para").style.fontSize = "25px";
document.getElementById("para").style.border = "4px solid red";
}
</script>
100
</body>
</html>
In HTML, we can use the ondblclick attribute to create a double click event.
Syntax
Now, we see the syntax of creating double click event in HTML and
in javascript (without using addEventListener() method or by using
the addEventListener() method).
In HTML
1. <element ondblclick = "fun()">
In JavaScript
1. object.ondblclick = function() { myScript };
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1 id = "heading" ondblclick = "fun()"> Hello world :):) </h1>
<h2> Double Click the text "Hello world" to see the effect. </h2>
101
<p> This is an example of using the <b> ondblclick </b> attribute. </p>
<script>
function fun() {
document.getElementById("heading").innerHTML = " Welcome to the Digitinstitute.in";
}
</script>
</body>
</html>
<body>
<h1 id = "heading"> Hello world :):) </h1>
<h2> Double Click the text "Hello world" to see the effect. </h2>
<p> This is an example of creating the double click event using JavaScript. </p>
<script>
document.getElementById("heading").ondblclick = function() { fun() };
function fun() {
document.getElementById("heading").innerHTML = " Welcome to the Digitinstitute.in";
}
</script>
</body>
</html>
<body>
102
<h1 id = "heading"> Hello world :):) </h1>
<h2> Double Click the text "Hello world" to see the effect. </h2>
<p> This is an example of creating the double click event using the <b> addEventListen
er() method </b>. </p>
<script>
document.getElementById("heading").addEventListener("dblclick", fun);
function fun() {
document.getElementById("heading").innerHTML = " Welcome to the Digitinstitute.in";
}
</script>
</body>
</html>
JavaScript onload
In JavaScript, this event can apply to launch a particular function when the page is fully
displayed. It can also be used to verify the type and version of the visitor's browser. We can
check what cookies a page uses by using the onload attribute.
In HTML, the onload attribute fires when an object has been loaded. The purpose of this
attribute is to execute a script when the associated element loads.
In HTML, the onload attribute is generally used with the <body> element to execute a
script once the content (including CSS files, images, scripts, etc.) of the webpage is
completely loaded. It is not necessary to use it only with <body> tag, as it can be used with
other HTML elements.
Syntax
1. window.onload = fun()
103
Example1
In this example, there is a div element with a height of 200px and a width of 200px.
Here, we are using the window.onload() to change the background color, width, and
height of the div element after loading the web page.
The background color is set to 'red', and width and height are set to 300px each.
<html>
<head>
<meta charset = " utf-8">
<title> window.onload() </title>
<style type = "text/css">
#bg{
width: 200px;
height: 200px;
border: 4px solid blue;
}
</style>
<script type = "text/javascript">
window.onload = function(){
document.getElementById("bg").style.backgroundColor = "red";
document.getElementById("bg").style.width = "300px";
document.getElementById("bg").style.height = "300px";
}
</script>
</head>
<body>
<h2> This is an example of window.onload() </h2>
<div id = "bg"></div>
</body>
</html>
104
JavaScript's window.outerWidth and window.outerHeight events. We can also use
the JavaScript's properties such as innerWidth, innerHeight, clientWidth,
ClientHeight, offsetWidth, offsetHeight to get the size of an element.
In HTML, we can use the onresize attribute and assign a JavaScript function to it. We
can also use the JavaScript's addEventListener()
Syntax
In HTML
Example
In this example, we are using the HTML onresize attribute. Here, we are using
the window.outerWidth and window.outerHeight events of JavaScript to get the
height and width of the window.
When the user resizes the window, the updated width and height of the window will
be displayed on the screen. It will also display how many times the user tried to resize
the window. When we change the height of the window, the updated height will
change accordingly. Similarly, when we change the width of the window, the updated
width will change accordingly.
105
<!DOCTYPE html>
<html>
<head>
<script>
var i = 0;
function fun() {
var res = "Width = " + window.outerWidth + "<br>" + "Height = " + window.outerHeight;
document.getElementById("para").innerHTML = res;
var res1 = i += 1;
document.getElementById("s1").innerHTML = res1;
}
</script>
</head>
<body onresize = "fun()">
<h3> This is an example of using onresize attribute. </h3>
<p> Try to resize the browser's window to see the effect. </p>
<!DOCTYPE html>
<html>
106
<head>
</head>
<body>
<h3> This is an example of using JavaScript's onresize event. </h3>
<p> Try to resize the browser's window to see the effect. </p>
function fun() {
var res = "Width = " + window.outerWidth + "<br>" + "Height = " + window.outerHeight;
document.getElementById("para").innerHTML = res;
var res1 = i += 1;
document.getElementById("s1").innerHTML = res1;
}
</script>
</body>
</html>
In exception handling:
107
A throw statement is used to raise an exception. It means when an abnormal condition occurs,
an exception is thrown using throw.
The thrown exception is handled by wrapping the code into the try…catch block. If an
error is present, the catch block will execute, else only the try block statements will get
executed.
Thus, in a programming language, there can be different types of errors which may
disturb the proper execution of the program.
Types of Errors
While coding, there can be three types of errors in the code:
Error Object
When a runtime error occurs, it creates and throws an Error object. Such an object can
be used as a base for the user-defined exceptions too. An error object has two
properties:
Although Error is a generic constructor, there are following standard built-in error
types or error constructors beside it:
1. EvalError: It creates an instance for the error that occurred in the eval(), which is a
global function used for evaluating the js string code.
2. InternalError: It creates an instance when the js engine throws an internal error.
3. RangeError: It creates an instance for the error that occurs when a numeric variable or
parameter is out of its valid range.
108
4. ReferenceError: It creates an instance for the error that occurs when an invalid
reference is de-referenced.
5. SyntaxError: An instance is created for the syntax error that may occur while parsing
the eval().
6. TypeError: When a variable is not a valid type, an instance is created for such an error.
7. URIError: An instance is created for the error that occurs when invalid parameters are
passed in encodeURI() or decodeURI().
o throw statements
o try…catch statements
o try…catch…finally statements.
JavaScript try…catch
A try…catch is a commonly used statement in various programming languages.
Basically, it is used to handle the error-prone part of the code. It initially tests the code
for all possible errors it may contain, then it implements actions to tackle those errors
(if occur). A good programming approach is to keep the complex code within the
try…catch statements.
try{} statement: Here, the code which needs possible error testing is kept within the
try block. In case any error occur, it passes to the catch{} block for taking suitable
actions and handle the error. Otherwise, it executes the code written within.
catch{} statement: This block handles the error of the code by executing the set of
statements written within the block. This block contains either the user-defined
exception handler or the built-in handler. This block executes only when any error-
prone code needs to be handled in the try block. Otherwise, the catch block is skipped.
109
Syntax:
try{
expression; } //code to be written.
catch(error){
expression; } // code for handling the error.
Throw Statement
Throw statements are used for throwing user-defined errors. User can define and
throw their own custom errors. When throw statement is executed, the statements
present after it will not execute. The control will directly pass to the catch block.
Syntax:
1. throw exception;
try…catch…throw syntax
try{
throw exception; // user can define their own exception
}
catch(error){
expression; } // code for handling exception.
110
<html>
<head>Exception Handling</head>
<body>
<script>
try {
throw new Error('This is the throw keyword'); //user-defined throw statement.
}
catch (e) {
document.write(e.message); // This will generate an error message
}
</script>
</body>
</html>
With the help of throw statement, users can create their own errors.
try…catch…finally statements
Finally is an optional block of statements which is executed after the execution of try
and catch statements. Finally block does not hold for the exception to be thrown. Any
exception is thrown or not, finally block code, if present, will definitely execute. It does
not care for the output too.
Syntax:
try{
expression;
}
catch(error){
111
expression;
}
finally{
expression; } //Executable code
try…catch…finally example
<html>
<head>Exception Handling</head>
<body>
<script>
try{
var a=2;
if(a==2)
document.write("ok");
}
catch(Error){
document.write("Error found"+e.message);
}
finally{
document.write("Value of a is 2 ");
}
</script>
</body>
</html>
<script>
var address=
{
112
company:"Digitinstitute",
city:"Noida",
state:"UP",
fullAddress:function()
{
return this.company+" "+this.city+" "+this.state;
}
};
var fetch=address.fullAddress();
document.writeln(fetch);
</script>
113