KEMBAR78
Unit 2 Notes | PDF | Dynamic Web Page | Java Script
0% found this document useful (0 votes)
12 views46 pages

Unit 2 Notes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views46 pages

Unit 2 Notes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

22UAD502 FULL STACK DEVELOPMENT UNIT II

UNIT-II CLIENT SIDE PROGRAMMING

An introduction to JavaScript – JavaScript DOM Model - Exception


Handling – Validation - Built-in objects - Event Handling - DHTML with
JavaScript – JSON Introduction -Syntax – Function Files

INTRODUCTION
Javascript is a dynamic computer programming language. It is lightweight
and most commonly used as a part of web pages, whose implementations allow
client-side script to interact with the user and make dynamic pages. It is an
interpreted programming language with object-oriented capabilities.

JavaScript was first known as LiveScript, but Netscape changed its name to
JavaScript, possibly because of the excitement being generated by Java.
JavaScript made its first appearance in Netscape 2.0 in 1995 with the name
LiveScript. The general-purpose core of the language has been embedded in
Netscape, Internet Explorer, and other web browsers.

Client-side JavaScript
Client-side JavaScript is the most common form of the language. The script should
be included in or referenced by an HTML document for the code to be interpreted
by the browser.
It means that a web page need not be a static HTML, but can include programs
that interact with the user, control the browser, and dynamically create HTML
content.
The JavaScript client-side mechanism provides many advantages over traditional
CGI server-side scripts. For example, you might use JavaScript to check if the
user has entered a valid e-mail address in a form field.
The JavaScript code is executed when the user submits the form, and only if all
the entries are valid, they would be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link
navigation, and other actions that the user initiates explicitly or implicitly.
Advantages of JavaScript
• Less server interaction − You can validate user input before sending the page
off to the server. This saves server traffic, which means less load on your server.
• Immediate feedback to the visitors − They don't have to wait for a page reload
to see if they have forgotten to enter something.
• Increased interactivity − You can create interfaces that react when the user
hovers over them with a mouse or activates them via the keyboard.
• Richer interfaces − You can use JavaScript to include such items as drag-and-
drop components and sliders to give a Rich Interface to your site visitors.
22UAD502 FULL STACK DEVELOPMENT UNIT II

Limitations of JavaScript
• Client-side JavaScript does not allow the reading or writing of files. This has
been kept for security reason.
• JavaScript cannot be used for networking applications because there is no such
support available.
• JavaScript doesn't have any multithreading or multiprocessor capabilities.
JavaScript can be implemented using JavaScript statements that are placed
within the<script>... </script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within you
web page, but it is normally recommended that you should keep it within the
<head> tags.
The <script> tag alerts the browser program to start interpreting all the text
between these tags as a script. A simple syntax of your JavaScript will appear as
follows.
The script tag takes two important attributes –
• Language − This attribute specifies what scripting language you are using.
Typically, its value will be javascript. Although recent versions of HTML (and
XHTML, its successor) have phased out the use of this attribute.
• Type − This attribute is what is now recommended to indicate the scripting
language in use and its value should be set to "text/javascript".
So your JavaScript segment will look like −
<scriptlanguage="javascript"type="text/javascript">
JavaScript code
</script>
22UAD502 FULL STACK DEVELOPMENT UNIT II

INCLUDING JAVASCRIPT IN HTML FILE


There is a flexibility given to include JavaScript code anywhere in an HTML
document. However the most preferred ways to include JavaScript in an HTML
file are as follows −
• Script in <head>...</head> section.
• Script in <body>...</body> section.
• Script in <body>...</body> and <head>...</head> sections.
• Script in an external file and then include in <head>...</head> section.
In the following section, we will see how we can place JavaScript in an HTML
file in different ways.
JavaScript in <head>...</head> section
If you want to have a script run on some event, such as when a user clicks
somewhere, then you will place that script in the head as follows –
<html><head><script type="text/javascript">
<!--
FunctionsayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
This code will produce the following results −
JavaScript in <body>...</body> section
If you need a script to run as the page loads so that the script generates content in
the page, then the script goes in the <body> portion of the document. In this case,
you would not have any function defined using JavaScript. Take a look at the
following code.
<html>

<head>
</head>

<body>

<script type="text/javascript">
<!--
22UAD502 FULL STACK DEVELOPMENT UNIT II

document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>
This code will produce the following results −
JavaScript in <body> and <head> Sections
You can put your JavaScript code in <head> and <body> section altogether as
follows −
<html>
<head>
<script type="text/javascript">
<!--
FunctionsayHello() {
alert("Hello World")
}
//-->
</script>
</head>

<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>

<input type="button" onclick="sayHello()" value="Say Hello" />

</body>
</html>
This code will produce the following result −
JavaScript in External File
As you begin to work more extensively with JavaScript, you will be likely to find
that there are cases where you are reusing identical JavaScript code on multiple
pages of a site.
You are not restricted to be maintaining identical code in multiple HTML files.
The script tag provides a mechanism to allow you to store JavaScript in an
external file and then include it into your HTML files.
22UAD502 FULL STACK DEVELOPMENT UNIT II

Here is an example to show how you can include an external JavaScript file in
your HTML code using script tag and its src attribute.
<html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
.......
</body>
</html>
To use JavaScript from an external file source, you need to write all your
JavaScript source code in a simple text file with the extension ".js" and then
include that file as shown above.
For example, you can keep the following content in filename.js file and then you
can usesayHello function in your HTML file after including the filename.js file.
FunctionsayHello() {
alert("Hello World")
}

JAVASCRIPT OUTPUT
JavaScript does NOT have any built-in print or display functions.
JavaScript Display Possibilities
JavaScript can "display" data in different ways:
• Writing into an alert box, using window.alert().
• Writing into the HTML output using document.write().
• Writing into an HTML element, using innerHTML.
• Writing into the browser console, using console.log().

Using window.alert()
You can use an alert box to display data:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body></html>
22UAD502 FULL STACK DEVELOPMENT UNIT II

Using document.write()
For testing purposes, it is convenient to use document.write():
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html>
Using document.write() after an HTML document is fully loaded, will delete all
existing HTML:
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<button onclick="document.write(5 + 6)">Try it</button>

</body>
</html>
Using innerHTML
To access an HTML element, JavaScript can use
the document.getElementById(id) method.
The id attribute defines the HTML element. The innerHTML property defines
the HTML content:
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My First Paragraph</p>
<p id="demo"></p>
22UAD502 FULL STACK DEVELOPMENT UNIT II

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>

</body>
</html>
Using console.log()
In your browser, you can use the console.log() method to display data.
Activate the browser console with F12, and select "Console" in the menu.
Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
console.log(5 + 6);
</script>

</body>
</html>
SYNTAX OF JAVASCRIPT
JavaScript syntax is the set of rules, how JavaScript programs are constructed.
A computer program is a list of "instructions" to be "executed" by the
computer.
In a programming language, these program instructions are
called statements.JavaScript is a programming language.
JavaScript statements are separated by semicolons.
var x = 5;
var y = 6;
var z = x + y;

Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
Values
22UAD502 FULL STACK DEVELOPMENT UNIT II

The JavaScript syntax defines two types of values: Fixed values and variable
values.
Fixed values are called literals. Variable values are called variables.
Variables
In a programming language, variables are used to store data values.
JavaScript uses the var keyword to define variables.
An equal sign is used to assign values to variables.
In this example, x is defined as a variable. Then, x is assigned (given) the value
6:
var x;

x = 6;
Operators
JavaScript uses an assignment operator ( = ) to assign values to variables:
var x = 5;
var y = 6;

JavaScript uses arithmetic operators ( + - * / ) to compute values:


(5 + 6) * 10

Expressions
An expression is a combination of values, variables, and operators, which
computes to a value.
The computation is called an evaluation.
For example, 5 * 10 evaluates to 50:
5 * 10
Expressions can also contain variable values:
x * 10
The values can be of various types, such as numbers and strings.
For example, "John" + " " + "Doe", evaluates to "John Doe":
"John" + " " + "Doe"
Keywords
Keywords are used to identify actions to be performed.The var keyword tells
the browser to create a new variable:
var x = 5 + 6;
var y = x * 10;
Comments in JavaScript
JavaScript supports both C-style and C++-style comments, Thus −
• Any text between a // and the end of a line is treated as a comment and is
ignored by JavaScript.
22UAD502 FULL STACK DEVELOPMENT UNIT II

• Any text between the characters /* and */ is treated as a comment. This may
span multiple lines.
• JavaScript also recognizes the HTML comment opening sequence <!--.
JavaScript treats this as a single-line comment, just as it does the // comment.
• The HTML comment closing sequence --> is not recognized by JavaScript so it
should be written as //-->.
Identifiers
Identifiers are names.
In JavaScript, identifiers are used to name variables (and keywords, and
functions, and labels).
The rules for legal names are much the same in most programming languages.
In JavaScript, the first character must be a letter, an underscore (_), or a dollar
sign ($).
Subsequent characters may be letters, digits, underscores, or dollar signs.

FUNCTIONS
• A function is a block of code designed to perform a particular task.
• A function is a group of reusable code which can be called anywhere in your
program. This eliminates the need of writing the same code again and again. It
helps programmers in writing modular codes. Functions allow a programmer to
divide a big program into a number of small and manageable functions.
• A JavaScript function is executed when "something" invokes it (calls it).
Syntax
A JavaScript function is defined with the function keyword, followed by
a name, followed by parentheses ().
function name(parameter1, parameter2, parameter3) {
code to be executed
}
Function parameters are the names listed in the function
definition.Function arguments are the real values received by the function when
it is invoked.Inside the function, the arguments are used as local variables.
function myFunction(p1, p2) {
return p1 * p2; // The function returns the product of p1 and p2
}
Function Invocation
The code inside the function will execute when "something" invokes (calls) the
function:
• When an event occurs (when a user clicks a button)
• When it is invoked (called) from JavaScript code
• Automatically (self invoked)
22UAD502 FULL STACK DEVELOPMENT UNIT II

<html><head>
<script type="text/javascript">
FunctionsayHello(name, age)
{
document.write (name + " is " + age + " years old.");
}
</script>

</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello('Zara', 7)" value="Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
return Statement
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.
<html>
<head>
<script type="text/javascript">
function concatenate(first, last)
{
var full;
full = first + last;
return full;
}

functionsecondFunction()
{
var result;
result = concatenate('Zara', 'Ali');
document.write (result );
}
</script>
</head>
<body>
22UAD502 FULL STACK DEVELOPMENT UNIT II

<p>Click the following button to call the function</p>


<form>
<input type="button" onclick="secondFunction()" value="Call Function">
<form>

<p>Use different parameters inside the function and then try...</p>

</body>
</html>
Nested Functions
Function inside another function is known as Nested Functions.
<html>
<head>
<script type="text/javascript">
<!--
function hypotenuse(a, b) {
function square(x) { return x*x; }
returnMath.sqrt(square(a) + square(b));
}
functionsecondFunction(){
var result;
result = hypotenuse(1,2);
document.write( result );
}
//-->
</script>
</head>
<body>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form>
</body>
</html>
Function Constructors
The function statement is not the only way to define a new function; you can define
your function dynamically using Function() constructor along with the new
operator.
Note − Constructor is a terminology from Object Oriented Programming. You
may not feel comfortable for the first time, which is OK.
22UAD502 FULL STACK DEVELOPMENT UNIT II

Syntax
Following is the syntax to create a function using Function( ) constructor along
with thenew operator.
<script type="text/javascript">
Var variablename = new Function(Arg1, Arg2..., "Function Body");
</script>
The Function() constructor expects any number of string arguments. The last
argument is the body of the function – it can contain arbitrary JavaScript
statements, separated from each other by semicolons.
Notice that the Function() constructor is not passed any argument that specifies a
name for the function it creates. The unnamed functions created with the
Function() constructor are called anonymous functions.
<html>
<head>
<script type="text/javascript">
<!--
Var func = new Function("x", "y", "return x*y;");
functionsecondFunction(){
var result;
result = func(10,20);
document.write( result );
}
//-->
</script>
</head>
<body>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form></body></html>
Function literals
Function literals which is another new way of defining functions. A function
literal is an expression that defines an unnamed function.
Syntax
The syntax for a function literal is much like a function statement, except that it
is used as an expression rather than a statement and no function name is required.
<script type="text/javascript">
var variablename = function(Argument List){
Function Body
};
22UAD502 FULL STACK DEVELOPMENT UNIT II

</script>
Syntactically, you can specify a function name while creating a literal function
as follows.
<script type="text/javascript">
Var variablename = function FunctionName(Argument List){
Function Body
};
</script>
But this name does not have any significance, so it is not worthwhile.
<html>
<head>
<script type="text/javascript">
var func = function(x,y){ return x*y };
functionsecondFunction(){
var result;
result = func(10,20);
document.write( result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form>
</body></html>
OBJECTS
Objects are composed of attributes. If an attribute contains a function, it is
considered to be a method of the object, otherwise the attribute is considered a
property.
In real life, a car is an object.
A car has properties like weight and color, and methods like start and stop:
All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but the methods are performed at different times.
var car = "Fiat";
Objects are variables too. But objects can contain many values.
var car = {type:"Fiat", model:500, color:"white"};

Properties
22UAD502 FULL STACK DEVELOPMENT UNIT II

The name:values pairs (in JavaScript objects) are called properties.


var person = {firstName:"XYZ", lastName:"ABC", age:20};
Example
<!DOCTYPE html><html>
<body>
<p id="demo"></p>
<script>
var person = {firstName:"XYZ", lastName:"ABC", age:20};
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>
</body></html>
Accessing Object Properties
You can access object properties in two ways:
objectName.propertyName
or
objectName[propertyName]
<!DOCTYPE html>
<html><body>
<p id="demo1"></p>
<p id="demo"></p>
<script>
var person = {
firstName: "XYZ", OUTPUT
lastName : "ABC",
id : 5566 XYZ ABC
}; XYZ ABC
document.getElementById("demo").innerHTML =person.firs tName + " " +
person.lastName;
document.getElementById("demo1").innerHTML =person["firstName"] + " "
+ person.lastName;
</script>
</body></html>
Methods
Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.
Methods are the functions that let the object do something or let something be
done to it. There is a small difference between a function and a method – at a
function is a standalone unit of statements and a method is attached to an object
and can be referenced by the thiskeyword.
22UAD502 FULL STACK DEVELOPMENT UNIT II

Methods are useful for everything from displaying the contents of the object to
the screen to performing complex mathematical operations on a group of local
properties and parameters.
User-Defined Objects
All user-defined objects and built-in objects are descendants of an object called
Object.
The new Operator
The new operator is used to create an instance of an object. To create an object,
the new operator is followed by the constructor method.
In the following example, the constructor methods are Object(), Array(), and
Date(). These constructors are built-in JavaScript functions.
var employee = new Object();
var books = new Array("C++", "Perl", "Java");
var day = new Date("August 15, 1947");
The Object() Constructor
A constructor is a function that creates and initializes an object. JavaScript
provides a special constructor function called Object() to build the object. The
return value of theObject() constructor is assigned to a variable.
The variable contains a reference to the new object. The properties assigned to the
object are not variables and are not defined with the var keyword.
<html><head>
<title>User-defined objects</title>
<script type="text/javascript">
var book = new Object(); // Create the object
book.subject = "C++"; // Assign properties to the object
book.author = "Ira Pohl"; OUTPUT:
</script>
</head> Book name is : C++
<body>
Book author is : Ira Pohl
<script type="text/javascript">
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>
</body></html>
Example 2:
<html><head>
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author){
this.title = title;
22UAD502 FULL STACK DEVELOPMENT UNIT II

this.author = author;
}
</script> OUTPUT:
</head>
Book name is : C++
<body>
<script type="text/javascript"> Book author is : Ira Pohl
varmyBook = new book("C++", "Ira Pohl");
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
</script>
</body></html>
Defining Methods for an Object
<html>
<head>
<title>User-defined objects</title>

<script type="text/javascript">
// Define a function which will work as a method
FunctionaddPrice(amount){
this.price = amount;
}
function book(title, author){
this.title = title;
this.author = author;
this.addPrice = addPrice; // Assign that method as property.
}
</script> OUTPUT:
</head> Book name is : C++
<body>
<script type="text/javascript"> Book author is : Ira Pohl
varmyBook = new book("C++", "Ira Pohl"); Book priceis : 100
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script></body></html>
NUMBER OBJECT
The Number object represents numerical date, either integers or floating-point
numbers. In general, you do not need to worry about Number objects because
22UAD502 FULL STACK DEVELOPMENT UNIT II

the browser automatically converts number literals to instances of the number


class.
Syntax
The syntax for creating a number object is as follows –
var val = new Number(number);
In the place of number, if you provide any non-number argument, then the
argument cannot be converted into a number, it returns NaN (Not-a-Number).
Converting Variables to Numbers
There are 3 JavaScript functions that can be used to convert variables to
numbers:
• The Number() method
• The parseInt() method
• The parseFloat() method
These methods are not number methods, but global JavaScript methods.
The Number() Method - can be used to convert JavaScript variables to
numbers:
x = true;
Number(x); // returns 1
x = false;
Number(x); // returns 0
x = new Date();
Number(x); // returns 1404568027739
x = "10"
Number(x); // returns 10
x = "10 20"
Number(x); // returns NaN
The parseInt() Method - parses a string and returns a whole number. Spaces
are allowed. Only the first number is returned:
parseInt("10"); // returns 10
parseInt("10.33"); // returns 10
parseInt("10 20 30"); // returns 10
parseInt("10 years"); // returns 10
parseInt("years 10"); // returns NaN
The parseFloat() Method - parses a string and returns a number. Spaces are
allowed. Only the first number is returned:
parseFloat("10"); // returns 10
parseFloat("10.33"); // returns 10.33
parseFloat("10 20 30"); // returns 10
parseFloat("10 years"); // returns 10
parseFloat("years 10"); // returns NaN
22UAD502 FULL STACK DEVELOPMENT UNIT II

The valueOf() Method - returns a number as a number.


var x = 123;
x.valueOf(); // returns 123 from variable x
(123).valueOf(); // returns 123 from literal 123
(100 + 23).valueOf(); // returns 123 from expression 100 + 23
Global Methods
JavaScript global functions can be used on all JavaScript data types.
These are the most relevant methods, when working with numbers:
Method Description
Number() Returns a number, converted from its
parseFloat() Parses its argument and returns a floating point
parseInt() Parses its argument and returns an integer
Number Methods
JavaScript number methods are methods that can be used on numbers:
Method Description
toString() Returns a number as a string
toExponential() Returns a string, with a number rounded and written using
toFixed() Returns a string, with a number rounded and written with a specified
number of decimals.

toPrecision() Returns a string, with a number written with a specified length


valueOf() Returns a number as a number
<!DOCTYPE html><html>
<body>
<button onclick="myFunction()">Demo</button>
<p id="demo"></p>
<script>
FunctionmyFunction() {
var x1 = true;
var x2 = false;
var x3 = new Date();
var x4 = "999";
var x5 = "999 888";
22UAD502 FULL STACK DEVELOPMENT UNIT II

var x6 = parseInt("40 years");


var x7 = parseFloat("36.00");
var x8 = isNaN("x6");
var n =
Number(x1) + "<br>" +
Number(x2) + "<br>" +
Number(x3) + "<br>" +
Number(x4) + "<br>" +
Number(x5)+ "<br>"+
x6 +"<br>" + x7 + "<br>" + x8 + "<br>" + String(x3);
document.getElementById("demo").innerHTML = n;
}
</script>
</body></html>
BOOLEAN OBJECT
The Boolean object represents two values, either "true" or "false".
If value parameter is omitted or is 0, -0, null, false, NaN, undefined, or the
empty string (""), the object has an initial value of false.
Syntax
Use the following syntax to create a boolean object.
varval = new Boolean(value);
Method Description
toSource() Returns a string containing the source of the Boolean object;
toString() Returns a string of either "true" or "false" depending upon the
value of the object.

valueOf() Returns the primitive value of the Boolean object.


<!DOCTYPE html>
<html><body>
<button onclick="myFunction()">Check</button>
<p id="demo"></p>
<script>
functionmyFunction()
{
document.getElementById("demo").innerHTML = Boolean( 10 > 9);
}
</script>
22UAD502 FULL STACK DEVELOPMENT UNIT II

</body></html>
ARRAY OBJECT
The Array object lets you store multiple values in a single variable. It stores a
fixed-size sequential collection of elements of the same type. An array is used to
store a collection of data, but it is often more useful to think of an array as a
collection of variables of the same type.
Syntax
var fruits = new Array( "apple", "orange", "mango" );
OR
var fruits = [ "apple", "orange", "mango" ]; //easiest method - literal
You will use ordinal numbers to access and to set values inside an array as
follows.
fruits[0] is the first element
fruits[1] is the second element
fruits[2] is the third element
Method Description
concat() Joins two or more arrays, and returns a copy of the joined arrays
indexOf() Search the array for an element and returns its position
join() Joins all elements of an array into a string
lastIndexOf() Search the array for an element, starting at the end, and returns its
pop() Removes the last element of an array, and returns that element
push() Adds new elements to the end of an array, and returns the new
reverse() Reverses the order of the elements in an array
shift() Removes the first element of an array, and returns that element
slice() Selects a part of an array, and returns the new array
sort() Sorts the elements of an array
splice() Adds/Removes elements from an array
toString() Converts an array to a string, and returns the result
unshift() Adds new elements to the beginning of an array, and returns the
22UAD502 FULL STACK DEVELOPMENT UNIT II

valueOf() Returns the primitive value of an array

Example:
<!DOCTYPE html><html>
<body>
<button onclick="myNumber()">Sorting of Numbers</button>
<p id="demo"></p>
<p id="demo1"></p>
<button onclick="myFruits()">Sorting of Alphabets</button>
<p id="demo2"></p>
<button onclick="myList()">Listing Fruits</button>
<p id="demo3"></p>

<script>
functionmyFruits() {
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); //to add an element to the array
fruits[fruits.length] = "Pomegranate"
fruits[6]="Grapes"
document.getElementById("demo2").innerHTML = fruits;
fruits.sort();
fruits.reverse();
document.getElementById("demo2").innerHTML = fruits;
}

functionmyNumber() {
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
document.getElementById("demo").innerHTML = points;
points.sort(function(a, b){return b-a});
document.getElementById("demo1").innerHTML = points;

functionmyList()
{
var index;
var text = "<ul>";
var fruits = ["Banana", "Orange", "Apple", "Mango"];
22UAD502 FULL STACK DEVELOPMENT UNIT II

for (index = 0; index <fruits.length; index++) {


text += "<li>" + fruits[index] + "</li>";
}
text += "</ul>";
document.getElementById("demo3").innerHTML = text;
}
</script>
</body></html>

DATE OBJECT
Method Description
getDate() Returns the day of the month (from 1-31)
getDay() Returns the day of the week (from 0-6)
getFullYear() Returns the year (four digits)
getHours() Returns the hour (from 0-23)
getMilliseconds() Returns the milliseconds (from 0-999)
getMinutes() Returns the minutes (from 0-59)
getMonth() Returns the month (from 0-11)
getSeconds() Returns the seconds (from 0-59)
22UAD502 FULL STACK DEVELOPMENT UNIT II

getTime() Returns the number of milliseconds since midnight Jan


getTimezoneOffset() Returns the time difference between UTC time and local
getUTCDate() Returns the day of the month, according to universal
getUTCDay() Returns the day of the week, according to universal time
parse() Parses a date string and returns the number of
setDate() Sets the day of the month of a date object
setFullYear() Sets the year (four digits) of a date object
setHours() Sets the hour of a date object
setMilliseconds() Sets the milliseconds of a date object
setMinutes() Set the minutes of a date object
setMonth() Sets the month of a date object
setSeconds() Sets the seconds of a date object
setTime() Sets a date to a specified number of milliseconds
after/before January 1, 1970

setUTCDate() Sets the day of the month of a date object, according to


toDateString() Converts the date portion of a Date object into a
toString() Converts a Date object to a string
UTC() Returns the number of milliseconds in a date since
midnight of January 1, 1970, according to UTC time

valueOf() Returns the primitive value of a Date object

<!DOCTYPE html><html>
<body>
<button onclick="myFunction()">Print Date</button>
<script>
FunctionmyFunction() {
22UAD502 FULL STACK DEVELOPMENT UNIT II

var d = new Date();


var m = d.getMonth();
var day = d.getDay();
document.write(d + "<br> ");
document.write("The Day is :"+ day + "<br>");
document.write(d.getHours()+":" +d.getMinutes()+":"+d.getSeconds()+"<br>");
document.write(d.getDate() +"/" +d.getMonth()+"/"+d.getFullYear()+"<br>");
d.setDate(23);
document.write(d.getDate() +"/" +d.getMonth()+"/"+d.getFullYear()+"<br>");
}
</script></body></html>

MATH OBJECT
The Math object allows you to perform mathematical tasks on numbers.
Constants
Math.E // returns Euler's number
Math.PI // returns PI
Math.SQRT2 // returns the square root of 2
Math.SQRT1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of 2
Math.LN10 // returns the natural logarithm of 10
Math.LOG2E // returns base 2 logarithm of E
Math.LOG10E // returns base 10 logarithm of E
Method Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
22UAD502 FULL STACK DEVELOPMENT UNIT II

atan(x) Returns the arctangent of x as a numeric value between -PI/2 and


atan2(y,x) Returns the arctangent of the quotient of its arguments
ceil(x) Returns x, rounded upwards to the nearest integer
cos(x) Returns the cosine of x (x is in radians)
exp(x) Returns the value of Ex
floor(x) Returns x, rounded downwards to the nearest integer
log(x) Returns the natural logarithm (base E) of x
max(x,y,z,...,n) Returns the number with the highest value
min(x,y,z,...,n) Returns the number with the lowest value
pow(x,y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Rounds x to the nearest integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Math Object</button>

<script>
FunctionmyFunction() {
document.write(Math.min(0, 150, 30, 20, -8, -200));
document.write("<br>");
document.write(Math.max(0, 150, 30, 20, -8, -200));
document.write("<br>");
document.write(Math.random());
22UAD502 FULL STACK DEVELOPMENT UNIT II

document.write("<br>");
document.write(Math.round(4.7888));
document.write("<br>");
document.write(Math.SQRT2);
document.write("<br>");
document.write(Math.SQRT1_2);
document.write("<br>");
}
</script>
</body></html>

STRING OBJECTS
A JavaScript string simply stores a series of characters like "John Doe".
A string can be any text inside quotes. You can use single or double quotes:
var answer = "It's alright";
var answer = "He is called 'Johnny'";
var answer = 'He is called "Johnny"';
String Length
The length of a string is found in the built in property length:
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
Special Characters
Because strings must be written within quotes, JavaScript will misunderstand
this string:
var y = "We are the so-called "Vikings" from the north."
The string will be chopped to "We are the so-called ".
The solution to avoid this problem, is to use the \ escape character.
The backslash escape character turns special characters into string characters:
var x = 'It\'s alright';
var y = "We are the so-called \"Vikings\" from the north."
22UAD502 FULL STACK DEVELOPMENT UNIT II

The escape character (\) can also be used to insert other special characters in a
string.
This is the list of special characters that can be added to a text string with the
backslash sign:
Code Outputs

\' single quote


\" double quote
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed
String Methods
Method Description

charAt() Returns the character at the specified index (position)


charCodeAt() Returns the Unicode of the character at the specified index
concat() Joins two or more strings, and returns a copy of the joined strings
fromCharCode Converts Unicode values to characters
indexOf() Returns the position of the first found occurrence of a specified
lastIndexOf() Returns the position of the last found occurrence of a specified value
localeCompar Compares two strings in the current locale
match() Searches a string for a match against a regular expression, and
replace() Searches a string for a value and returns a new string with the value
search() Searches a string for a value and returns the position of the match
22UAD502 FULL STACK DEVELOPMENT UNIT II

slice() Extracts a part of a string and returns a new string


split() Splits a string into an array of substrings
substr() Extracts a part of a string from a start position through a number of
substring() Extracts a part of a string between two specified positions
toLocaleLowe Converts a string to lowercase letters, according to the host's locale
toLocaleUpper Converts a string to uppercase letters, according to the host's locale
toLowerCase() Converts a string to lowercase letters
toString() Returns the value of a String object
toUpperCase() Converts a string to uppercase letters
trim() Removes whitespace from both ends of a string
valueOf() Returns the primitive value of a String object
<html>
<head>
<title>Strings</title>
</head>
<body>
<script type="text/javascript">
varstr = "Apples are round, and apples are juicy.";
varsplitted = str.split(" ", 3);
var y = "We are the so-called \"Vikings\" from the north.";
document.write(splitted );
document.write("<br>");
document.write(y);
document.write("<br>");
document.write(y.toUpperCase());
document.write("<br>");
document.write(y.search('V'));
document.write("<br>");
document.write(y.slice(22,-2));
document.write("<br>");
document.write(y.substring(22,29));
</script></body></html>
22UAD502 FULL STACK DEVELOPMENT UNIT II

REGULAR EXPRESSIONS
• A regular expression is a sequence of characters that forms a search pattern.
• When you search for data in a text, you can use this search pattern to describe
what you are searching for.
• A regular expression can be a single character, or a more complicated pattern.
• Regular expressions can be used to perform all types of text search and text
replace operations.
Syntax
A regular expression could be defined with the RegExp () constructor, as
follows −
var pattern = /pattern/attibutes;
OR
var pattern = new RegExp(pattern, attributes);
Here is the description of the parameters –
• pattern − A string that specifies the pattern of the regular expression or another
regular expression.
• attributes − An optional string containing any of the "g", "i", and "m" attributes
that specify global, case-insensitive, and multiline matches, respectively.
Brackets
Brackets ([]) have a special meaning when used in the context of regular
expressions. They are used to find a range of characters.
Expression Description
[...] Any one character between the brackets.
[^...] Any one character not between the brackets.
[0-9] It matches any decimal digit from 0 through 9.
[a-z] It matches any character from lowercase a through lowercase z.
22UAD502 FULL STACK DEVELOPMENT UNIT II

[A-Z] It matches any character from uppercase A through uppercase Z.


[a-Z] It matches any character from lowercase a through uppercase Z.
The ranges shown above are general; you could also use the range [0-3] to match
any decimal digit ranging from 0 through 3, or the range [b-v] to match any
lowercase character ranging from b through v.
Quantifiers
The frequency or position of bracketed character sequences and single characters
can be denoted by a special character. Each special character has a specific
connotation. The +, *, ?, and $ flags all follow a character sequence.
Expression Description
p+ It matches any string containing at least one p.
p* It matches any string containing zero or more p's.
p? It matches any string containing one or more p's.
p{N} It matches any string containing a sequence of N p's
p{2,3} It matches any string containing a sequence of two or three p's.
p{2, } It matches any string containing a sequence of at least two p's.
p$ It matches any string with p at the end of it.
^p It matches any string with p at the beginning of it.
Examples
Following examples explain more about matching characters.
Expression Description
[^a-zA-Z] It matches any string not containing any of the characters
ranging from athrough z and A through Z.
p.p It matches any string containing p, followed by any character,
in turn followed by another p.

^.{2}$ It matches any string containing exactly two characters.


<b>(.*)</b> It matches any string enclosed within <b> and </b>.
22UAD502 FULL STACK DEVELOPMENT UNIT II

p(hp)* It matches any string containing a p followed by zero or more


instances of the sequence hp.

Literal characters
Character Description
Alphanumeric Itself
\0 The NUL character (\u0000)
\t Tab (\u0009)
\n Newline (\u000A)
\v Vertical tab (\u000B)
\f Form feed (\u000C)
\r Carriage return (\u000D)
\xnn The Latin character specified by the hexadecimal number nn;
for example, \x0A is the same as \n

\uxxxx The Unicode character specified by the hexadecimal number


xxxx; for example, \u0009 is the same as \t
\cX The control character ^X; for example, \cJ is equivalent to the
newline character \n
Metacharacters
A metacharacter is simply an alphabetical character preceded by a backslash that
acts to give the combination a special meaning.
For instance, you can search for a large sum of money using the '\d'
metacharacter:/([\d]+)000/, Here \d will search for any string of numerical
character.
The following table lists a set of metacharacters which can be used in PERL Style
Regular Expressions.
Character Description
. a single character
\s a whitespace character (space, tab, newline)
\S non-whitespace character
22UAD502 FULL STACK DEVELOPMENT UNIT II

\d a digit (0-9)
\D a non-digit
\w a word character (a-z, A-Z, 0-9, _)
\W a non-word character
[\b] a literal backspace (special case).
[aeiou] matches a single character in the given set
[^aeiou] matches a single character outside the given set
(foo|bar|baz) matches any of the alternatives specified
Modifiers
Several modifiers are available that can simplify the way you work
with regexps, like case sensitivity, searching in multiple lines, etc.
Modifier Description
i Perform case-insensitive matching.
M Specifies that if the string has newline or carriage return characters, the
^ and $ operators will now match against a newline boundary, instead of

G Performs a global matchthat is, find all matches rather than stopping
after the first match.

Search & Replace


In JavaScript, regular expressions are often used with the two string methods:
search() and replace().
The search() method uses an expression to search for a match, and returns the
position of the match.
The replace() method returns a modified string where the pattern is replaced.

Using String search() With a Regular Expression


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Search</button>
22UAD502 FULL STACK DEVELOPMENT UNIT II

<p id="demo"></p>
<script>
FunctionmyFunction() {
varstr = "Velammal Institute of Technology";
var n = str.search(/Institute/i);
document.getElementById("demo").innerHTML = n;
}
</script>
</body></html>

Using String replace() With a Regular Expression


<!DOCTYPE html>
<html>
<body>
<p>Replace "velammal" with "Vellore" in the paragraph below:</p>
<button onclick="myFunction()">Replace</button>

<p id="demo">Please visit Velammal Institute of Technology!</p>


<script>
FunctionmyFunction()
{
varstr = document.getElementById("demo").innerHTML;
var txt = str.replace(/velammal/i,"Vellore");
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>

FORM VALIDATION USING JAVASCRIPT REG ULAR EXPRESSIONS


Usage Pattern
1.Username [Min 8 Chars and alpha /^[a-z0-9]{8,}/ i
numeric characters)
2. Email ID /^[a-z0-9._-]+@[a-z]+.[a-z.]{2,5}$/i
3. Date of Birth /^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$/i
4. Mobile Number /^([+0-9]{1,3})?([0-9]{10,11})$/i
22UAD502 FULL STACK DEVELOPMENT UNIT II

5. Web Site URL /^[http://]+[www]?.[0-9a-z_.]+.[a-


z.]{2,5}$/i
6. Pincode /^[0-9]{6}$/i

DOCUMENT OBJECT MODEL (THE DOM MODEL)


When a web page is loaded, the browser creates a Document Object Model of
the page.
Every web page resides inside a browser window which can be considered as an
object.
A Document object represents the HTML document that is displayed in that
window. The Document object has various properties that refer to other objects
which allow access to and modification of document content.
The way document content is accessed and modified is called the Document
Object Model, or DOM. The Objects are organized in a hierarchy. This
hierarchical structure applies to the organization of objects in a Web document.
The HTML DOM model is constructed as a tree of Objects:

With the object model, JavaScript gets all the power it needs to create dynamic
HTML:
• JavaScript can change all the HTML elements in the page
• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the page
22UAD502 FULL STACK DEVELOPMENT UNIT II

• JavaScript can create new HTML events in the page


What is the DOM?
The DOM is a W3C (World Wide Web Consortium) standard.
The DOM defines a standard for accessing documents:
"The W3C Document Object Model (DOM) is a platform and language-neutral
interface that allows programs and scripts to dynamically access and update the
content, structure, and style of a document."
The W3C DOM standard is separated into 3 different parts:
• Core DOM - standard model for all document types
• XML DOM - standard model for XML documents
• HTML DOM - standard model for HTML documents
What is the HTML DOM?
The HTML DOM is a standard object model and programming interface for
HTML. It defines:
• The HTML elements as objects
• The properties of all HTML elements
• The methods to access all HTML elements
• The events for all HTML elements
In other words: The HTML DOM is a standard for how to get, change, add,
or delete HTML elements.
HTML DOM methods are actions you can perform (on HTML Elements)
HTML DOM properties are values (of HTML Elements) that you can set or
change

The DOM Programming Interface


The HTML DOM can be accessed with JavaScript (and with other programming
languages).
In the DOM, all HTML elements are defined as objects.
The programming interface is the properties and methods of each object.
A property is a value that you can get or set (like changing the content of an
HTML element).
A method is an action you can do (like add or deleting an HTML element).

Example
The following example changes the content (the innerHTML) of the <p>
element with id="demo":
<html>
<body>

<p id="demo"></p>
22UAD502 FULL STACK DEVELOPMENT UNIT II

<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>

</body>
</html>
In the example above, getElementById is a method, while innerHTML is
a property.
The getElementById Method
The most common way to access an HTML element is to use the id of the
element.
In the example above the getElementById method used id="demo" to find the
element.
The innerHTML Property
The easiest way to get the content of an element is by using
the innerHTML property.
The innerHTML property is useful for getting or replacing the content of HTML
elements.
The HTML DOM Document
In the HTML DOM object model, the document object represents your web
page.
The document object is the owner of all other objects in your web page.
If you want to access objects in an HTML page, you always start with accessing
the document object.
Below are some examples of how you can use the document object to access and
manipulate HTML.
Finding HTML Elements
Method Description
document.getElementById() Find an element by element id
document.getElementsByTagName() Find elements by tag name
document.getElementsByClassName() Find elements by class name
Changing HTML Elements
Method Description

element.innerHTML= Change the inner HTML of an element


22UAD502 FULL STACK DEVELOPMENT UNIT II

element.attribute= Change the attribute of an HTML element


element.setAttribute(attribute,value) Change the attribute of an HTML element
element.style.property= Change the style of an HTML element
Adding and Deleting Elements
Method Description
document.createElement() Create an HTML element
document.removeChild() Remove an HTML element
document.appendChild() Add an HTML element
document.replaceChild() Replace an HTML element
document.write(text) Write into the HTML output
Adding Events Handlers
Method Description
document.getElementById(id).onclick=function(){code} Adding event handler
Finding HTML Objects
The first HTML DOM Level 1 (1998), defined 11 HTML objects, object
collections, and properties. These are still valid in HTML5.
Later, in HTML DOM Level 3, more objects, collections, and properties were
added.
Property Description DOM

document.anchors Returns all <a> elements that have a 1


name attribute

document.applets Returns all <applet> 1


elements (Deprecated in HTML5)

document.baseURI Returns the absolute base URI of the 3


document

document.body Returns the <body> element 1

document.cookie Returns the document's cookie 1


22UAD502 FULL STACK DEVELOPMENT UNIT II

document.doctype Returns the document's doctype 3

document.documentElement Returns the <html> element 3

document.documentMode Returns the mode used by the browser 3

document.documentURI Returns the URI of the document 3

document.domain Returns the domain name of the 1


document server

document.domConfig Obsolete. Returns the DOM 3


configuration

document.embeds Returns all <embed> elements 3

document.forms Returns all <form> elements 1

document.head Returns the <head> element 3

document.images Returns all <img> elements 1

document.implementation Returns the DOM implementation 3

document.inputEncoding Returns the document's encoding 3


(character set)

document.lastModified Returns the date and time the 3


document was updated

document.links Returns all <area> and <a> elements 1


that have a href attribute

document.readyState Returns the (loading) status of the 3


document

document.referrer Returns the URI of the referrer (the 1


linking document)

document.scripts Returns all <script> elements 3

document.strictErrorChecking Returns if error checking is enforced 3


22UAD502 FULL STACK DEVELOPMENT UNIT II

document.title Returns the <title> element 1

document.URL Returns the complete URL of the 1


document
EVENT HANDLING
A JavaScript can be executed when an event occurs, like when a user clicks on
an HTML element.
To execute code when a user clicks on an element, add JavaScript code to an
HTML event attribute:
onclick=JavaScript
Examples of HTML events:
• When a user clicks the mouse
• When a web page has loaded
• When an image has been loaded
• When the mouse moves over an element
• When an input field is changed
• When an HTML form is submitted
• When a user strokes a key
In this example, the content of the <h1> element is changed when a user clicks
on it:
Example
<!DOCTYPE html>
<html>
<body>

<h1 onclick="this.innerHTML='Ooops!'">Click on this text!</h1>

</body>
</html>
In this example, a function is called from the event handler:
<!DOCTYPE html>
<html>
<body>

<h1 onclick="changeText(this)">Click on this text!</h1>

<script>
function changeText(id) {
id.innerHTML = "Ooops!";
22UAD502 FULL STACK DEVELOPMENT UNIT II

}
</script>

</body>
</html>
Assign Events Using the HTML DOM
The HTML DOM allows you to assign events to HTML elements using
JavaScript:
Assign an onclick event to a button element:
<script>
document.getElementById("myBtn").onclick = displayDate;
</script>
In the example above, a function named displayDate is assigned to an HTML
element with the id="myBtn".
The function will be executed when the button is clicked.
The onload and onunload Events
The onload and onunload events are triggered when the user enters or leaves the
page.
The onload event can be used to check the visitor's browser type and browser
version, and load the proper version of the web page based on the information.
The onload and onunload events can be used to deal with cookies.
<body onload="checkCookies()">
The onchange Event
The onchangeevent are often used in combination with validation of input fields.
Below is an example of how to use the onchange. The upperCase() function will
be called when a user changes the content of an input field.
<input type="text" id="fname" onchange="upperCase()">

<!DOCTYPE html>
<html>
<head>
<script>
FunctionmyFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</head>
<body>
22UAD502 FULL STACK DEVELOPMENT UNIT II

Enter your name: <input type="text" id="fname" onchange="myFunction()">


<p>When you leave the input field, a function is triggered which transforms the
input text to upper case.</p>

</body>
</html>
The onmouseover and onmouseout Events
The onmouseover and onmouseout events can be used to trigger a function when
the user mouses over, or out of, an HTML element.
<!DOCTYPE html>
<html>
<body>
<div onmouseover="mOver(this)" onmouseout="mOut(this)"
style="background-color:#D94A38;width:120px;height:20px;padding:40px;">
Mouse Over Me</div>
<script>
FunctionmOver(obj) {
obj.innerHTML = "Thank You"
}

FunctionmOut(obj) {
obj.innerHTML = "Mouse Over Me"
}
</script>
</body></html>
The onmousedown, onmouseup and onclick Events
The onmousedown, onmouseup, and onclick events are all parts of a mouse- click.
First when a mouse-button is clicked, the onmousedown event is triggered, then,
when the mouse-button is released, the onmouseup event is triggered, finally,
when the mouse-click is completed, the onclick event is triggered.
<!DOCTYPE html>
<html>
<body>

<div onmousedown="mDown(this)" onmouseup="mUp(this)"


style="background-color:#D94A38;width:90px;height:20px;padding:40px;">
Click Me</div>
<script>
FunctionmDown(obj) {
obj.style.backgroundColor = "#1ec5e5";
22UAD502 FULL STACK DEVELOPMENT UNIT II

obj.innerHTML = "Release Me";


}

FunctionmUp(obj) {
obj.style.backgroundColor="#D94A38";
obj.innerHTML="Thank You";
}
</script>

</body>
</html>
The onfocus()
Change the background-color of an input field when it gets focus.
<!DOCTYPE html>
<html>
<head>
<script>
FunctionmyFunction(x) {
x.style.background = "yellow";
}
</script>
</head>
<body>
Enter your name: <input type="text" onfocus="myFunction(this)">
<p>When the input field gets focus, a function is triggered which changes the
background-color.</p>
</body>
</html>
Create a web page using two image files, which switch between one another
as the mouse pointer moves over the images. Use the on Mouse Over and on
Mouse Out
<!DOCTYPE html>
<html>
<head>
<script>
Functionlighton() {
document.getElementById('myimage').src = "bulbon.gif";
}
Functionlightoff() {
document.getElementById('myimage').src = "bulboff.gif";
22UAD502 FULL STACK DEVELOPMENT UNIT II

}
</script>
</head>

<body>

<img id="myimage" onmousedown="lighton()" onmouseup="lightoff()"


src="bulboff.gif" width="100" height="180" />

<p>Click mouse and hold down!</p>

</body>
</html>
EXCEPTION HANDLING
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime
Errors, and (c) Logical Errors.
Syntax Errors
Syntax errors, also called parsing errors, occur at compile time in traditional
programming languages and at interpret time in JavaScript.
Runtime Errors
Runtime errors, also called exceptions, occur during execution (after
compilation/interpretation).
Logical Errors
Logic errors can be the most difficult type of errors to track down. These errors
are not the result of a syntax or runtime error. Instead, they occur when you make
a mistake in the logic that drives your script and you do not get the result you
expected.
The try...catch...finally Statement
The try statement lets you test a block of code for errors.
The catch statement lets you handle the error.
The throw statement lets you create custom errors.
The finally statement lets you execute code, after try and catch, regardless of the
result.
JavaScript implements the try...catch...finally construct as well as
the throw operator to handle exceptions.
You can catch programmer-generated and runtime exceptions, but you
cannot catchJavaScript syntax errors.
Here is the try...catch...finally block syntax −
<scripttype="text/javascript">
22UAD502 FULL STACK DEVELOPMENT UNIT II

<!--
try{
// Code to run
[break;]
}

catch( e ){
// Code to run if an exception occurs
[break;]
}

[ finally{
// Code that is always executed regardless of
// an exception occurring
}]
//-->
</script>
The try block must be followed by either exactly one catch block or
one finally block (or one of both). When an exception occurs in the try block, the
exception is placed in e and the catch block is executed. The optional
finally block executes unconditionally after try/catch.
<!DOCTYPE html>
<html>
<body>

<p>Please input a number between 5 and 10:</p>


<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="message"></p>
<script>
FunctionmyFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
22UAD502 FULL STACK DEVELOPMENT UNIT II

if(x < 5) throw "too low";


if(x > 10) throw "too high";
}
catch(err) {
message.innerHTML = "Input is " + err;
}
}
</script>
</body></html>
The finally Statement
The finally statement lets you execute code, after try and catch, regardless of the
result:
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {
Block of code to be executed regardless of the try / catch result
}
Example:
<!DOCTYPE html>
<html>
<body>
<p>Please input a number between 5 and 10:</ p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>

<p id="message"></p>
<script>
FunctionmyFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "is empty";
if(isNaN(x)) throw "is not a number";
x = Number(x);
22UAD502 FULL STACK DEVELOPMENT UNIT II

if(x > 10) throw "is too high";


if(x < 5) throw "is too low";
}
catch(err) {
message.innerHTML = "Input " + err;
}
finally {
document.getElementById("demo").value = "";
}
}
</script>
</body></html>

You might also like