Javascript Unit I
Javascript Unit I
Javascript Unit I
What is JavaScript?
JavaScript (js) is a light-weight object-oriented programming language which is used by several
websites for scripting the webpages. It is an interpreted, full-fledged programming language
that enables dynamic interactivity on websites when applied to an HTML document. It was
introduced in the year 1995 for adding programs to the webpages in the Netscape Navigator
browser. Since then, it has been adopted by all other graphical web browsers. With JavaScript,
users can build modern web applications to interact directly without reloading the page every
time. The traditional website uses js to provide several forms of interactivity and simplicity.
JavaScript was introduced in 1995 as a way to add programs to web pages in the Netscape
Navigator browser. The language has since been adopted by all other major graphical web
browsers. It has made modern web applications possible—applications with which you can
interact directly, without doing a page reload for every action. But it is also used in more
traditional websites to provide various forms of interactivity and cleverness.
It is important to note that JavaScript has almost nothing to do with the programming language
named Java. The similar name was inspired by marketing considerations, rather than good
judgment. When JavaScript was introduced, the Java language was being heavily marketed and
was gaining popularity. Someone thought it was a good idea to ride on the coattails of
this success. Now we are stuck with the name.
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.
We call this three-step sequence the save-switch-reload sequence. You will perform this
sequence so often as you script that the physical act will quickly become second nature to you.
How you arrange your application windows and effect the save-switch-reload sequence varies
according to your operating system.
In web site production, after you tweak your markup, style sheet, and scripts to your liking on
your own computer, you’ll upload them to your server using an FTP (File Transfer Protocol)
program.
There are also online editors, but for now let’s keep it simple. One of the advantages of doing
your work off-line on your own computer is that you don’t even have to have an active Internet
connection during this stage of web site development.
Selecting the right tools for the job
The best way to learn JavaScript is to type the HTML and scripting code into documents in a
text editor. Your choice of editor is up to you, although we provide some guidelines for
choosing.
An important factor to consider in your choice of editor is how easy it is to save standard text
files with an .html filename extension. In the case of Windows, any program that not only saves
the file as text by default, but also enables you to set the extension to .htm or .html, prevents a
great deal of problems. If you use Microsoft Word, for example, the program tries to save files
as binary Word files — something that no web browser can load. To save the file initially as
a .txt or .html extension file requires mucking around in the Save As dialog box. This is truly a
nuisance. Perhaps more importantly, a word processor such as Microsoft Word opens with a lot
of default settings that may make desktop publishing easier but can frustrate a programmer,
such as inserting spaces around words and automatically replacing straight quotes with curly
quotes.
Setting its defaults to make it programmer-friendly will make it less useful as a word processor.
Finally, we urge you not to create documents in Word and ‘‘save them as a web page.’’ This
will generate an HTML document that will look much like the word processing document on
which it’s based, but the actual HTML coding it produces will be bloated and redundant — a far
cry from the sleek and elegant code that we hope you will be producing after you read this
book. Word just isn’t the right tool for this job.
Nothing’s wrong with using bare-essentials text editors. In Windows, that includes the Word-
Pad program or a more fully featured product such as Visual Studio or the shareware editor
called TextPad. For Mac OS X, the bundled TextEdit application is also fine. Favorites among
Mac HTML authors and scripters include BBEdit (Bare Bones Software) and SubEthaEdit
(www.codingmonkeys.de/subethaedit).
Choosing a browser
The other component that is required for learning JavaScript is the browser. You don’t have to
be connected to the Internet to test your scripts in the browser. You can perform all testing
offline. This means you can learn JavaScript and create cool, scripted web pages with a laptop
computer — even on a boat in the middle of an ocean.
The browser brand and version you use are up to you. Because the tutorial chapters in this book
teach the W3C DOM syntax, you should be using a recent browser. Any of the following will
get you through the tutorial: Internet Explorer 5 or later (Windows or Macintosh); any Mozilla-
based browser (including Firefox, Netscape 7 or later, and Camino); Apple Safari; and Opera 7
or later.
objects
In JavaScript, an object is an unordered collection of key-value pairs. Each key-value pair is
called a property.
The key of a property can be a string. The value of a property can be any value, e.g., a string,
a number, an array, and even a function.
JavaScript provides you with many ways to create an object. The most commonly used one is to
use the object literal notation.
The following example creates an empty object using the object literal notation:
To create an object with properties, you use the key:value within the curly braces.
let person = {
firstName: 'John',
lastName: 'Doe'
};
The person object has two properties firstName and lastName with the corresponding
values 'John' and 'Doe'.
When an object has multiple properties, you use a comma (,) to separate them like the above
example.
To access a property of an object, you use one of two notations: the dot notation and array-like
notation.
The following illustrates how to use the dot notation to access a property of an object:
objectName.propertyName
For example, to access the firstName property of the person object, you use the following
expression:
person.firstName
This example creates a person object and shows the first name and last name to the console:
let person = {
firstName: 'John',
lastName: 'Doe'
};
console.log(person.firstName);
console.log(person.lastName);
The following illustrates how to access the value of an object’s property via the array-like
nottion:
objectName['propertyName']
Example:
let person = {
firstName: 'John',
lastName: 'Doe'
};
console.log(person['firstName']);
console.log(person['lastName']);
When a property name contains spaces, you need to place it inside quotes. For example, the
following address object has the 'building no' as a property:
let address = {
state: 'CA',
country: 'USA'
};
To change the value of a property, you use the assignment operator (=).
For example:
let person = {
firstName: 'John',
lastName: 'Doe'
};
person.firstName = 'Jane';
console.log(person);
In this example, we changed the value of the firstName property of the person object
from 'John' to 'Jane'.
Adding a new property to an object
Unlike objects in other programming languages such as Java and C#, you can add a property to
an object after object creation.
The following statement adds the age property to the person object and assigns 25 to it:
person.age = 25;
delete objectName.propertyName;
delete person.age;
propertyName in objectName
The following example creates an employee object and uses the in operator to check if
the ssn and employeeId properties exist in the object:
console.log('ssn' in employee);
console.log('employeeId' in employee);
variables
A JavaScript variable is simply a name of storage location.You can place data into these
containers and then refer to the data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are declared
with the var keyword as follows.
<scripttype="text/javascript">
var money;
var name;
</script>
You can also declare multiple variables with the same var keyword as follows −
<scripttype="text/javascript">
Storing a value in a variable is called variable initialization. You can do variable initialization
at the time of variable creation or at a later point in time when you need that variable.
JavaScript is untyped language. This means that a JavaScript variable can hold a value of any
data type. Unlike many other languages, you don't have to tell JavaScript during variable
declaration what type of value the variable will hold. The value type of a variable can change
during the execution of a program and JavaScript takes care of it automatically.
There are some rules while declaring a JavaScript variable (also known as identifiers).
Global Variables − A global variable has global scope which means it can be defined
anywhere in your JavaScript code.A variable i.e. declared outside the function or declared with
window object is known as global variable.
<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>
Local Variables − A local variable will be visible only within a function where it is defined.
Function parameters are always local to that function.
<script>
function abc(){
var x=10;//local variable
}
</script>
Data Types
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:
JavaScript operators are symbols that are used to perform operations on operands
1. Arithmetic 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:
3. Bitwise Operators
The bitwise operators perform bitwise operations on operands. The bitwise operators are as
follows:
4. Logical Operators
= Assign 10+10 = 20
Making comparisons
Difference between JavaScript and HTML
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.;
Mouse events:
mouseover onmouseover When the cursor of the mouse comes 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
Form events:
Event Event Description
Performed Handler
change onchange When the user modifies or changes the value of a form
element
Window/Document events
load onload When the browser finishes the loading of the page
unload onunload When the visitor leaves the current webpage, the browser
unloads it
resize onresize When the visitor resizes the window of the browser
Examples:
Click Event
<html>
<body>
<!--
function clickevent()
document.write("This is JavaTpoint");
//-->
</script>
<form>
</form>
</body>
</html>
MouseOver Event
<html>
<head>
</head>
<body>
<!--
function mouseoverevent()
alert("This is JavaTpoint");
//-->
</script>
</body>
</html>
Focus Event
<html>
<head> Javascript Events</head>
<body>
<script>
<!--
function focusevent()
document.getElementById("input1").style.background=" aqua";
//-->
</script>
</body>
</html>
Keydown Event
<html>
<head> Javascript Events</head>
<body>
<script>
<!--
function keydownevent()
document.getElementById("input1");
alert("Pressed a key");
//-->
</script>
</body>
</html>
Load event
<html>
<head>Javascript Events</head>
</br>
<script>
<!--
//-->
</script>
</body>
</html>
Save this file to your hard drive as hello-world.html, and open it in your browser. Figure 3-3
shows the page as it appears in the browser after you’re finished. The precise appearance (or
voice, if you’re using a screen-reader) may vary slightly from one browser to the next, since at
this point we’re relying on the default style sheet in the browser to render the page.
The head of this page contains two required elements: a meta tag that declares the MIME type
and character set, and a title. The body consists of a headline and a paragraph of text, pure and
simple.
Save this file as hello-world.js. It consists of just three JavaScript statements: the first gets the
current date, the second composes a brief message, and the third displays the message.
To enable this JavaScript program to act on your HTML document, add a new script tag to the
head section of the HTML
The HTML script element tells the browser the type and name of the script file to combine with
the document. Because the src (source) attribute doesn’t include a path, the system assumes it’s
in
the same folder as the HTML file. Unlike the meta tag, every <script> tag must be closed with
</script>.
When you save the new JavaScript file and the modified HTML file, reload the HTML file in
your
browser.
A JavaScript alert().
The text we passed to alert() appears in what’s called a modal dialog. ‘‘Modal’’ means that you
can’t do anything more with the application (your browser) until you close the dialog. Notice
that the HTML headline and paragraph seem to have disappeared! No worries; they will appear
as soon as you click OK on the modal dialog. Why? The browser renders the HTML file from
top to bottom. It encounters the script tag in the head and runs the named JavaScript program
before it renders the HTML body. In this case, the modal dialog produced by the alert() method
halts the rendering of the rest of the page until we respond.
The link element tells the browser the type, relationship, and name of the style sheet to combine
with the document. Note that, like the meta tag and unlike the script tag, link is an ‘‘empty’’ tag
and does not take a separate closing tag. Because the src (source) attribute doesn’t include a
path, the system assumes it’s in the same folder as the HTML file. Every <script> tag must be
closed with </script>.
When you save these files and reload the HTML document in your browser (and click OK on
that modal dialog)
A styled page.
Internal vs. external scripts
JavaScript provides 3 places to put the JavaScript code: within body tag, within head tag and
external JavaScript file.
In the above example, we have displayed the dynamic content using JavaScript. Let’s see the
simple example of JavaScript that displays alert dialog box.
<script type="text/javascript">
alert("Hello Javatpoint");
</script>
Let’s see the same example of displaying alert dialog box of JavaScript that is contained inside
the head tag.
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.
<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello Javatpoint");
</script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
</form>
</body>
</html>
We can create external JavaScript file and embed it in many html page.
It provides code re usability because single JavaScript file can be used in several html pages.
An external JavaScript file must be saved by .js extension. It is recommended to embed all
JavaScript files into a single file. It increases the speed of the webpage.
create an external JavaScript file that prints Hello Javatpoint in a alert dialog box.
message.js
function msg(){
alert("Hello Javatpoint");
}
include the JavaScript file into html page. It calls the JavaScript function on button click.
index.html
<html>
<head>
<script type="text/javascript" src="message.js"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
1. The stealer may download the coder's code using the url of the js file.
2. If two js files are dependent on one another, then a failure in one file may affect the
execution of the other dependent file.
3. The web browser needs to make an additional http request to get the js code.
4. A tiny to a large change in the js code may cause unexpected results in all its dependent
files.
5. We need to check each file that depends on the commonly created external javascript file.
6. If it is a few lines of code, then better to implement the internal javascript code.
Comments in scripts
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.
1. To make code easy to understand It can be used to elaborate the code so that end user
can easily understand the code.
2. To avoid the unnecessary code It can also be used to avoid the code being executed.
Sometimes, we add the code to perform some action. But after sometime, there may be
need to disable the code. In such case, it is better to use comments.
1. Single-line Comment
It is represented by double forward slashes (//). It can be used before and after the statement.
Let’s see the example of single-line comment i.e. added before the statement.
<script>
// It is single line comment
document.write("hello javascript");
</script>
2. Multi-line Comment
It can be used to add single as well as multi line comments. So, it is more convenient.
It is represented by forward slash with asterisk then asterisk with forward slash.
For example:
<script>
/* It is multi line comment.
It will not be displayed */
document.write("example of javascript multiline comment");
</script>
NoScript
The noscript element is the converse of script. A JavaScript-aware browser will render the
contents of the noscript block if scripting has been turned off or if the browser doesn’t support a
scripting language invoked by a script element in the document. (Significantly, a legacy
browser that doesn’t support scripting at all and doesn’t recognize script-related tags will
likewise render the contents of both script and noscript blocks, which is why we comment out
the contents of a script block. A noscript block will therefore be rendered by all browsers when
scripting is not supported.)
You can display any standard HTML within the noscript tag set. It is a block-level element that
can contain paragraphs, lists, divisions, headings, and so on.
The conventional use of noscript is to present HTML content to display in the absence of
scripting support — a message such as, ‘‘This page would be more interesting if viewed with
JavaScript running,’’ for example, or an HTML hyperlink to a page that provides content that
would otherwise be inserted by Javascript.
Example:
<script>
document.write("Welcome to JavaTpoint")
</script>
<noscript>Sorry! Your browser does not support JavaScript.!</noscript>
alert dialogs
The alert() method in JavaScript is used to display a virtual alert box. It is mostly used to give a
warning message to the users. It displays an alert dialog box that consists of some specified
message (which is optional) and an OK button. When the dialog box pops up, we have to click
"OK" to proceed.
The alert dialog box takes the focus and forces the user to read the specified message. So, we
should avoid overusing this method because it stops the user from accessing the other parts of
the webpage until the box is closed.
Rather than showing the warnings or errors, the alert dialog box can be used for normal
messages such as 'welcome back', 'Hello XYZ', etc.
Syntax:
alert(message)
Values:
message: It is an optional string that specifies the text to display in the alert box. It consists of
the information that we want to show to the users.
<html>
<head>
<script type = "text/javascript">
function fun() {
JavaScript If statement
It evaluates the content only if expression is true. The signature of JavaScript if statement is
given below.
Syntax:
if(expression){
//content to be evaluated
}
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
It evaluates the content whether condition is true of false. The syntax of JavaScript if-else
statement is given below.
Syntax:
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
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.
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
JavaScript If...else if statement
It evaluates the content only if expression is true from several expressions. The signature of
JavaScript if else if statement is given below.
Syntax:
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
}
Example:
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
Flowchart of JavaScript If...else .. if statement
Getting confirmations from users
JavaScript confirm method invokes a function that asks the user for a confirmation dialogue on
a particular action. The confirm () method uses a window object to invoke a dialogue with a
question and two option buttons, OK and Cancel. If the user selects the OK option, it will
continue to the function execution; selecting the Cancel option will abort the block code's
execution.
It returns true if the user selects the OK option; otherwise, it returns false.
Syntax:
confirm("Select an Option!");
Parameters:
It takes a "message" value in string format to display in the confirmation dialogue you want to
show the user.
Return value:
The confirm method returns a Boolean output, either true or false, if the OK is selected.
A boolean indicating whether OK (true) or Cancel (false) was selected. If a browser ignores in-
page dialogues, then the returned value is always false.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="conf"></p>
<script>
function myFunction() {
var result;
if (r == true) {
} else {
document.getElementById("conf").innerHTML = result;
</script>
</body>
</html>
Creating prompts for users
The prompt() method in JavaScript is used to display a prompt box that prompts the user for
the input. It is generally used to take the input from the user before entering the page. It can be
written without using the window prefix. When the prompt box pops up, we have to click "OK"
or "Cancel" to proceed.
The box is displayed using the prompt() method, which takes two arguments: The first
argument is the label which displays in the text box, and the second argument is the default
string, which displays in the textbox. The prompt box consists of two buttons, OK and Cancel.
It returns null or the string entered by the user. When the user clicks "OK," the box returns the
input value. Otherwise, it returns null on clicking "Cancel".
The prompt box takes the focus and forces the user to read the specified message. So, it should
avoid overusing this method because it stops the user from accessing the other parts of the
webpage until the box is closed.
Syntax:
prompt(message, default)
Values
message: It is an optional parameter. It is the text displays to the user. We can omit this value if
we don't require to show anything in the prompt.
default: It is also an optional parameter. It is a string that contains the default value displayed in
the textbox.
In this example, there is a simple prompt box with a message and two buttons (OK and Cancel).
Here, there is an HTML button which is used for displaying the prompt box. We are using the
onclick attribute and call the fun() function where the prompt() is defined.
<html>
<head>
function fun() {
</script>
</head>
<body>
<form>
</form>
</body>
</html>
Understanding functions
JavaScript functions are used to perform operations. We can call JavaScript function many
times to reuse the code. Before we use a function, we need to define it. The most common way
to define a function in JavaScript is by using the function keyword, followed by a unique
function name, a list of parameters (that might be empty), and a statement block surrounded by
curly braces.
Let’s see the simple example of function in JavaScript that does not has arguments.
<html>
<head>
function sayHello() {
}
</script>
</head>
<body>
<form>
</form>
</body>
</html>
We can call function by passing arguments. These passed parameters can be captured inside the
function and any manipulation can be done over those parameters. A function can take multiple
parameters separated by comma. Let’s see the example of function that has one argument.
<html>
<head>
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
</form>
</body>
</html>
A JavaScript function can have an optional return statement. This is required if you want to
return a value from a function. This statement should be the last statement in a function.
For example, you can pass two numbers in a function and then you can expect the function to
return their multiplication in your calling program.
Example
Try the following example. It defines a function that takes two parameters and concatenates
them before returning the resultant in the calling program.
<html>
<head>
var full;
return full;
function secondFunction() {
var result;
document.write (result );
</script>
</head>
<body>
<form>
</form>
</body>
</html>
Making links smarter
Using switch/case statements
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
Synatax:
switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......
default:
code to be executed if above values are not matched;
}
Example:
<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>
Handling errors
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.
Types of Errors
1. Syntax Error: When a user makes a mistake in the pre-defined syntax of a programming
language, a syntax error may appear.
2. Runtime Error: When an error occurs during the execution of the program, such an
error is known as Runtime error. The codes which create runtime errors are known as
Exceptions. Thus, exception handlers are used for handling runtime errors.
3. Logical Error: An error which occurs when there is any logical mistake in the program
that may not produce the desired output, and may terminate abnormally. Such an error is
known as Logical error.
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:
JavaScript is a loosely-typed language. It does not give compile-time errors. So some times you
will get a runtime error for accessing an undefined variable or calling undefined function etc.
try
{
// code that may throw an error
}
catch(ex)
{
// code to be executed if an error occurs
}
finally{
// code to be executed regardless of an error occurs or not
}
try:
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:
write code to do something in catch block when an error occurs. The catch block can have
parameters that will give you error information. Generally catch block is used to log an error or
display specific messages to the user.
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.
finally:
code in the finally block will always be executed regardless of the occurrence of an error. The
finally block can be used to complete the remaining task or reset variables that might have
changed before error occurred in try block.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: Error Handling</h1>
<p id="errorMessage"></p>
<script>
try
{
var result = Sum(10, 20); // Sum is not defined yet
}
catch(ex)
{
document.getElementById("errorMessage").innerHTML = ex;
}
</script>
</body>
</html>
In the above example, we are calling function Sum, which is not defined yet. So, try block will
throw an error which will be handled by catch block. Ex includes error message that can be
displayed.
The finally block executes regardless of whatever happens.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: Error Handling</h1>
<script>
try
{
var result = Sum(10, 20); // Sum is not defined yet
}
catch(ex)
{
document.getElementById("errorMessage").innerHTML += ex;
}
finally{
document.getElementById("message").innerHTML = "finally block
executed";
}
</script>
</body>
</html>
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().