Ubit - Iii WT
Ubit - Iii WT
Ubit - Iii WT
Introduction
Features of JavaScript
Advantages of JavaScript
DHTML :
DHTML stands for Dynamic Hypertext Markup language i.e., Dynamic HTML.
Dynamic HTML is not a markup or programming language but it is a term that combines the
features of various web development technologies for creating the web pages dynamic and
interactive.
The DHTML application was introduced by Microsoft with the release of the 4 th version of IE
(Internet Explorer) in 1997.
Components of Dynamic HTML
o HTML 4.0
o CSS
o JavaScript
o DOM.
HTML 4.0
HTML is a client-side markup language, which is a core component of the DHTML. It defines
the structure of a web page with various defined basic elements or tags.
CSS
CSS stands for Cascading Style Sheet, which allows the web users or developers for
controlling the style and layout of the HTML elements on the web pages.
JavaScript
JavaScript is a scripting language which is done on a client-side. The various browser supports
JavaScript technology. DHTML uses the JavaScript technology for accessing, controlling, and
manipulating the HTML elements. The statements in JavaScript are the commands which tell
the browser for performing an action.
DOM
DOM is the document object model. It is a w3c standard, which is a standard interface of
programming for HTML. It is mainly used for defining the objects and properties of all
elements in HTML.
Uses of DHTML
o It is used for designing the animated and interactive web pages that are developed in
real-time.
o DHTML helps users by animating the text and images in their documents.
o It allows the authors for adding the effects on their pages.
o It also allows the page authors for including the drop-down menus or rollover buttons.
o This term is also used to create various browser-based action games.
o It is also used to add the ticker on various websites, which needs to refresh their content
automatically.
Features of DHTML
o Its simplest and main feature is that we can create the web page dynamically.
o Dynamic Style is a feature, that allows the users to alter the font, size, color, and
content of a web page.
o It provides the facility for using the events, methods, and properties. And, also provides
the feature of code reusability.
o It also provides the feature in browsers for data binding.
o Using DHTML, users can easily create dynamic fonts for their web sites or web pages.
o With the help of DHTML, users can easily change the tags and their properties.
2. It is used for developing and creating web 2. It is used for creating and designing the animated
pages. and interactive web sites or pages.
3. This markup language creates static web 3. This concept creates dynamic web pages.
pages.
4. It does not contain any server-side scripting 4. It may contain the code of server-side scripting.
code.
5. The files of HTML are stored with the .html 5. The files of DHTML are stored with the .dhtm
or .htm extension in a system. extension in a system.
6. A simple page which is created by a user 6. A page which is created by a user using the
without using the scripts or styles called as an HTML, CSS, DOM, and JavaScript technologies
HTML page. called a DHTML page.
7. This markup language does not need 7. This concept needs database connectivity because
database connectivity. it interacts with users.
o The web page functionality is enhanced because the DHTML uses low-bandwidth
effect.
DHTML JavaScript
JavaScript can be included in HTML pages, which creates the content of the page as dynamic.
We can easily type the JavaScript code within the <head> or <body> tag of a HTML page. If
we want to add the external source file of JavaScript, we can easily add using the <src>
attribute.
Following are the various examples, which describes how to use the JavaScript technology
with the DHTML:
Document.write() Method
Example 1: The following example simply uses the document.write() method of JavaScript
in the DHTML. In this example, we type the JavaScript code in the <body> tag.
1. <HTML>
2. <head>
3. <title>
4. Method of a JavaScript
5. </title>
6. </head>
7. <body>
8. <script type="text/javascript">
9. document.write("JavaTpoint");
10. </script>
11. </body>
12. </html>
13. Output:
JavaScript Variables
Example:
var a;
var b;
Example: var a, b;
Variable initialization
var a = 10;
var b = 20;
Variable Scope
1. Global Variable
<html>
<head>
<script type = "text/javascript">
count = 5; //Global variable
var a = 4; //Global variable
function funccount() // Function Declaration
{
count+=5; // Local variable
a+=4;
document.write("<b>Inside function Global Count: </b>"+count+"<br>");
document.write("<b>Inside function Global A: </b>"+a+"<br>");
}
</script>
</head>
<body>
<script type="text/javascript">
document.write("<b>Outside function Global Count: </b>"+count+"<br>");
document.write("<b>Outside function Global A: </b>"+a+"<br>");
funccount();
</script>
</body>
</html>
Output:
2. Local Variable
<html>
<head>
<script type="text/javascript">
function funccount(a) // Function with Argument
{
var count=5; // Local variable
count+=2;
document.write("<b>Inside Count: </b>"+count+"<br>");
a+=3;
document.write("<b>Inside A: </b>"+a+"<br>");
}
</script>
</head>
<body>
<script type="text/javascript">
var a=3, count = 0;
funccount(a);
document.write("<b>Outside Count: </b>"+count+"<br>");
document.write("<b>Outside A: </b> "+a+"<br>");
</script>
</body>
</html>
Output:
Inside Count: 7
Inside A: 6
Outside Count: 0
Outside A: 3
JavaScript String
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:
1. <script>
2. var str="This is string literal";
3. document.write(str);
4. </script>
Output:
The syntax of creating string object using new keyword is given below:
1. <script>
2. var stringname=new String("hello javascript string");
3. document.write(stringname);
4. </script>
Output:
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.
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.
The JavaScript String charAt() method returns the character at the given index.
1. <script>
2. var str="javascript";
3. document.write(str.charAt(2));
4. </script>
Output:
1. <script>
2. var s1="javascript ";
3. var s2="concat example";
4. var s3=s1.concat(s2);
5. document.write(s3);
6. </script>
Output:
The JavaScript String indexOf(str) method returns the index position of the given string.
1. <script>
2. var s1="javascript from javatpoint indexof";
3. var n=s1.indexOf("from");
4. document.write(n);
5. </script>
Output:
11
The JavaScript String lastIndexOf(str) method returns the last index position of the given
string.
1. <script>
2. var s1="javascript from javatpoint indexof";
3. var n=s1.lastIndexOf("java");
4. document.write(n);
5. </script>
Output:
16
The JavaScript String toLowerCase() method returns the given string in lowercase letters.
1. <script>
2. var s1="JavaScript toLowerCase Example";
3. var s2=s1.toLowerCase();
4. document.write(s2);
5. </script>
Output:
The JavaScript String toUpperCase() method returns the given string in uppercase letters.
1. <script>
2. var s1="JavaScript toUpperCase Example";
3. var s2=s1.toUpperCase();
4. document.write(s2);
5. </script>
Output:
The JavaScript String slice(beginIndex, endIndex) method returns the parts of string from
given beginIndex to endIndex. In slice() method, beginIndex is inclusive and endIndex is
exclusive.
1. <script>
2. var s1="abcdefgh";
3. var s2=s1.slice(2,5);
4. document.write(s2);
5. </script>
Output:
cde
8) JavaScript String trim() Method
The JavaScript String trim() method removes leading and trailing whitespaces from the string.
1. <script>
2. var s1=" javascript trim ";
3. var s2=s1.trim();
4. document.write(s2);
5. </script>
Output:
javascript trim
9) JavaScript String split() Method
1. <script>
2. var str="This is JavaTpoint website";
3. document.write(str.split(" ")); //splits the given string.
4. </script>
JavaScript provides different data types to hold different types of values. There are two types
of data types in JavaScript.
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:
There are five types of primitive data types in JavaScript. They are as follows:
Data Type Description
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
Arithmetic operators are used to perform arithmetic operations on the operands. The following
operators are known as JavaScript arithmetic operators.
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
/ Division 20/10 = 2
The JavaScript comparison operator compares the two operands. The comparison operators
are as follows:
The bitwise operators perform bitwise operations on operands. The bitwise operators are as
follows:
= Assign 10+10 = 20
+= Add and assign var a=10; a+=20; Now a = 30
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
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. }
Flowchart of JavaScript If statement
It evaluates the content whether condition is true of false. The syntax of JavaScript if-else
statement is given below.
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. }
Flowchart of JavaScript If...else statement
Let’s see the example of if-else statement in JavaScript to find out the even or odd number.
1. <script>
2. var a=20;
3. if(a%2==0){
4. document.write("a is even number");
5. }
6. else{
7. document.write("a is odd number");
8. }
9. </script>
It evaluates the content only if expression is true from several expressions. The signature of
JavaScript if else if statement is given below.
1. if(expression1){
2. //content to be evaluated if expression1 is true
3. }
4. else if(expression2){
5. //content to be evaluated if expression2 is true
6. }
7. else if(expression3){
8. //content to be evaluated if expression3 is true
9. }
10. else{
11. //content to be evaluated if no expression is true
12. }
1. <script>
2. var a=20;
3. if(a==10){
4. document.write("a is equal to 10");
5. }
6. else if(a==15){
7. document.write("a is equal to 15");
8. }
9. else if(a==20){
10. document.write("a is equal to 20");
11. }
12. else{
13. document.write("a is not equal to 10, 15 or 20");
14. }
15. </script>
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.
1. switch(expression){
2. case value1:
3. code to be executed;
4. break;
5. case value2:
6. code to be executed;
7. break;
8. ......
9.
10. default:
11. code to be executed if above values are not matched;
12. }
Let’s see the simple example of switch statement in javascript.
1. <script>
2. var grade='B';
3. var result;
4. switch(grade){
5. case 'A':
6. result="A Grade";
7. break;
8. case 'B':
9. result="B Grade";
10. break;
11. case 'C':
12. result="C Grade";
13. break;
14. default:
15. result="No Grade";
16. }
17. document.write(result);
18. </script>
1. <script>
2. var grade='B';
3. var result;
4. switch(grade){
5. case 'A':
6. result+=" A Grade";
7. case 'B':
8. result+=" B Grade";
9. case 'C':
10. result+=" C Grade";
11. default:
12. result+=" No Grade";
13. }
14. document.write(result);
15. </script>
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 compact. It is mostly used in array.
1. for loop
2. while loop
3. do-while loop
4. for-in loop
The JavaScript for loop iterates the elements for the fixed number of times. It should be used
if number of iteration is known. The syntax of for loop is given below.
1. <script>
2. for (i=1; i<=5; i++)
3. {
4. document.write(i + "<br/>")
5. }
6. </script>
Output:
1
2
3
4
5
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. }
1. <script>
2. var i=11;
3. while (i<=15)
4. {
5. document.write(i + "<br/>");
6. i++;
7. }
8. </script>
Output:
11
12
13
14
15
The JavaScript do while loop iterates the elements for the infinite number of times like while
loop. But, code is executed at least once whether condition is true or false. The syntax of do
while loop is given below.
1. do{
2. code to be executed
3. }while (condition);
1. <script>
2. var i=21;
3. do{
4. document.write(i + "<br/>");
5. i++;
6. }while (i<=25);
7. </script>
Output:
21
22
23
24
25
JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function many
times to reuse the code.
Advantage of JavaScript function
Let’s see the simple example of function in JavaScript that does not has arguments.
1. <script>
2. function msg(){
3. alert("hello! this is message");
4. }
5. </script>
6. <input type="button" onclick="msg()" value="call function"/>
We can call function by passing arguments. Let’s see the example of function that has one
argument.
1. <script>
2. function getcube(number){
3. alert(number*number*number);
4. }
5. </script>
6. <form>
7. <input type="button" value="click" onclick="getcube(4)"/>
8. </form>
We can call function that returns a value and use it in our program. Let’s see the example of
function that returns value.
1. <script>
2. function getInfo(){
3. return "hello javatpoint! How r u?";
4. }
5. </script>
6. <script>
7. document.write(getInfo());
8. </script>
Syntax
Parameter
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.
Example 1
1. <script>
2. var add=new Function("num1","num2","return num1+num2");
3. document.writeln(add(2,5));
4. </script>
Output:
7
Example 2
1. <script>
2. var pow=new Function("num1","num2","return Math.pow(num1,num2)");
3. document.writeln(pow(2,3));
4. </script>
Output:
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.
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.
1. Square Root of 17 is: <span id="p1"></span>
2. <script>
3. document.getElementById('p1').innerHTML=Math.sqrt(17);
4. </script>
Output:
Math.random()
Output:
Math.pow(m,n)
The JavaScript math.pow(m,n) method returns the m to the power of n that is mn.
Output:
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.
Output:
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.
Output:
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.
Math.abs(n)
The JavaScript math.abs(n) method returns the absolute value for the given number. For
example 4 for -4, 6.6 for -6.6 etc.
Output:
JavaScript Array
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
1. var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by , (comma).
Let's see the simple example of creating and using array in JavaScript.
1. <script>
2. var emp=["Sonoo","Vimal","Ratan"];
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br/>");
5. }
6. </script>
Sonoo
Vimal
Ratan
1. <script>
2. var i;
3. var emp = new Array();
4. emp[0] = "Arun";
5. emp[1] = "Varun";
6. emp[2] = "John";
7.
8. for (i=0;i<emp.length;i++){
9. document.write(emp[i] + "<br>");
10. }
11. </script>
Output of the above example
Arun
Varun
John
Here, you need to create instance of array by passing arguments in constructor so that we don't
have to provide value explicitly.
1. <script>
2. var emp=new Array("Jai","Vijay","Smith");
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br>");
5. }
6. </script>
Output
Jai
Vijay
Smith
Let's see the list of JavaScript array methods with their description.
Methods Description
concat() It returns a new array object that contains two or more merged arrays.
copywithin() It copies the part of the given array with its own elements and returns the
modified array.
entries() It creates an iterator object and a loop that iterates over each key/value pair.
every() It determines whether all the elements of an array are satisfying the provided
function conditions.
flatMap() It maps all array elements via mapping function, then flattens the result into a
new array.
from() It creates a new array carrying the exact copy of another array element.
filter() It returns the new array containing the elements that pass the provided
function conditions.
find() It returns the value of the first element in the given array that satisfies the
specified condition.
findIndex() It returns the index value of the first element in the given array that satisfies
the specified condition.
forEach() It invokes the provided function once for each element of an array.
includes() It checks whether the given array contains the specified element.
indexOf() It searches the specified element in the given array and returns the index of
the first match.
keys() It creates an iterator object that contains only the keys of the array, then loops
through these keys.
lastIndexOf() It searches the specified element in the given array and returns the index of
the last match.
map() It calls the specified function for every array element and returns the new
array
of() It creates a new array from a variable number of arguments, holding any type
of argument.
reduce(function, It executes a provided function for each value from left to right and reduces
initial) the array to a single value.
reduceRight() It executes a provided function for each value from right to left and reduces
the array to a single value.
some() It determines if any element of the array passes the test of the implemented
function.
slice() It returns a new array containing the copy of the part of the given array.
sort() It returns the element of the given array in a sorted order.
toString() It converts the elements of a specified array into string form, without affecting
the original array.
unshift() It adds one or more elements in the beginning of the given array.
values() It creates a new iterator object carrying values for each index in the array.
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)
1. object={property1:value1,property2:value2.....propertyN:valueN}
1. <script>
2. emp={id:102,name:"Shyam Kumar",salary:40000}
3. document.write(emp.id+" "+emp.name+" "+emp.salary);
4. </scrip>
Output of the above example
102 Shyam Kumar 40000
1. <script>
2. var emp=new Object();
3. emp.id=101;
4. emp.name="Ravi Malik";
5. emp.salary=50000;
6. document.write(emp.id+" "+emp.name+" "+emp.salary);
7. </script>
Output of the above example
101 Ravi 50000
3) By using an Object constructor
Here, you need to create function with arguments. Each argument value can be assigned in the
current object by using this keyword.
1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6. }
7. e=new emp(103,"Vimal Jaiswal",30000);
8.
9. document.write(e.id+" "+e.name+" "+e.salary);
10. </script>
We can define method in JavaScript object. But before defining method, we need to add
property in the function with same name as method.
1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6.
7. this.changeSalary=changeSalary;
8. function changeSalary(otherSalary){
9. this.salary=otherSalary;
10. }
11. }
12. e=new emp(103,"Sonoo Jaiswal",30000);
13. document.write(e.id+" "+e.name+" "+e.salary);
14. e.changeSalary(45000);
15. document.write("<br>"+e.id+" "+e.name+" "+e.salary);
16. </script>
Output of the above example
103 Sonoo Jaiswal 30000
103 Sonoo Jaiswal 45000
The JavaScript date object can be used to get year, month and day. You can display a timer
on the webpage by the help of JavaScript date object.
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
1. Date()
2. Date(milliseconds)
3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)
Let's see the list of JavaScript date methods with their description.
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.
getUTCDate() It returns the integer value between 1 and 31 that represents the day for the
specified date on the basis of universal time.
getUTCDay() It returns the integer value between 0 and 6 that represents the day of the
week on the basis of universal time.
getUTCFullYears() It returns the integer value that represents the year on the basis of universal
time.
getUTCHours() It returns the integer value between 0 and 23 that represents the hours on the
basis of universal time.
getUTCMinutes() It returns the integer value between 0 and 59 that represents the minutes on
the basis of universal time.
getUTCMonth() It returns the integer value between 0 and 11 that represents the month on the
basis of universal time.
getUTCSeconds() It returns the integer value between 0 and 60 that represents the seconds on
the basis of universal time.
setDate() It sets the day value for the specified date on the basis of local time.
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.
setMilliseconds() It sets the millisecond value for the specified date on the basis of local time.
setMinutes() It sets the minute value for the specified date on the basis of local time.
setMonth() It sets the month value for the specified date on the basis of local time.
setSeconds() It sets the second value for the specified date on the basis of local time.
setUTCDate() It sets the day value for the specified date on the basis of universal time.
setUTCDay() It sets the particular day of the week on the basis of universal time.
setUTCFullYears() It sets the year value for the specified date on the basis of universal time.
setUTCHours() It sets the hour value for the specified date on the basis of universal time.
setUTCMilliseconds() It sets the millisecond value for the specified date on the basis of universal
time.
setUTCMinutes() It sets the minute value for the specified date on the basis of universal time.
setUTCMonth() It sets the month value for the specified date on the basis of universal time.
setUTCSeconds() It sets the second value for the specified date on the basis of universal time.
toJSON() It returns a string representing the Date object. It also serializes the Date
object during JSON serialization.
toUTCString() It converts the specified date in the form of string using UTC time zone.
Let's see the simple example to print date object. It prints date and time both.
Output:
Current Date and Time: Mon Jun 05 2023 21:36:43 GMT+0530 (India Standard Time)
1. <script>
2. var date=new Date();
3. var day=date.getDate();
4. var month=date.getMonth()+1;
5. var year=date.getFullYear();
6. document.write("<br>Date is: "+day+"/"+month+"/"+year);
7. </script>
Output:
Output:
Let's see the simple example to display digital clock using JavaScript date object.
There are two ways to set interval in JavaScript: by setTimeout() or setInterval() method.
Output:
Current Time:
An exception signifies the presence of an abnormal condition which requires special operable
techniques. In programming terms, an exception is the anomalous code that breaks the normal
flow of the code. Such exceptions require specialized programming constructs for its
execution.
In programming, exception handling is a process or method used for handling the abnormal
statements in the code and executing them. It also enables to handle the flow control of the
code/program. For handling the code, various handlers are used that process the exception and
execute the code. For example, the Division of a non-zero value with zero will result into
infinity always, and it is an exception. Thus, with the help of exception handling, it can be
executed and handled.
In exception handling:
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
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.
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().
JavaScript try…catch
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.
Syntax:
1. try{
2. expression; } //code to be written.
3. catch(error){
4. expression; } // code for handling the error.
try…catch example
1. <html>
2. <head> Exception Handling</br></head>
3. <body>
4. <script>
5. try{
6. var a= ["34","32","5","31","24","44","67"]; //a is an array
7. document.write(a); // displays elements of a
8. document.write(b); //b is undefined but still trying to fetch its value. Thus catch block will be i
nvoked
9. }catch(e){
10. alert("There is error which shows "+e.message); //Handling error
11. }
12. </script>
13. </body>
14. </html>
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
1. try{
2. throw exception; // user can define their own exception
3. }
4. catch(error){
5. expression; } // code for handling exception.
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:
1. try{
2. expression;
3. }
4. catch(error){
5. expression;
6. }
7. finally{
8. expression; } //Executable code
try…catch…finally example
1. <html>
2. <head>Exception Handling</head>
3. <body>
4. <script>
5. try{
6. var a=2;
7. if(a==2)
8. document.write("ok");
9. }
10. catch(Error){
11. document.write("Error found"+e.message);
12. }
13. finally{
14. document.write("Value of a is 2 ");
15. }
16. </script>
17. </body>
18. </html>
{
DHTML with JavaScript - Data validation, opening a new window, messages and
confirmations, the status bar, different frames, rollover buttons, moving images
}