The Eduladder is a community of students, teachers, and programmers just interested to make you pass any exams. So we help you to solve your academic and programming questions fast.
In eduladder you can Ask,Answer,Listen,Earn and Download Questions and Question papers.
Watch related videos of your favorite subject.
Connect with students from different parts of the world.
Apply or Post Jobs, Courses ,Internships and Volunteering opportunity. For FREE
See Our team
Wondering how we keep quality?
Got unsolved questions? Ask Questions


You are here:Open notes-->VTU-->Programming-the-Web10CS73-unit-3

Programming the Web[10CS73] unit-3

3.1 Overview of Javascript
JavaScript is a sequence of statements to be executed by the browser. It is most popular 
scripting language on the internet, and works in all major browsers, such as IE, FireFox, 
chrome, opera safari. Prequisite ?HTML/XHTML
Origins
It is originally known as LiveScript, developed by Netscape. It become a joint venture of 
Netscape and Sun in 1995, and was renamed as JavaScript. It was standardized by the 
European computer Manufacturers Association as ECMA-262. ISO-16262. Current 
standard specifications can be found at
http://www.ecma-international.org/publications/standardsEcma-262.htm
Collections of JavaScript code scripts and not programs.
What is JavaScript?
1. JavaScript was designed to add interactivity to HTML pages.
2. JavaScript is a scripting language.
3. A scripting language is a lightweight programming language.
4. It is usually embedded directly into HTML pages.
5. JavaScript is an interpreted language (Scripts are executed without preliminary 
compilations)
JavaScript can be divided into three parts.
1. The Core: It is a heart of the language, including its operators, expressions, statements 
and subprograms.
2. Client Side: It is a collection of objects that support control of a browser and 
interactions with users. Eg. With JavaScript an XHTML document can be made to be 
responsible to user inputs. Such as mouse clicks and keyboard use.
3. Server side: It is a collection of objects that make the language useful on a Web
server. Eg. To support communication with a DBMS. Client side JavaScript is an 
XHTML embedded scripting language. We refer to every collection of JavaScript code as 
a script. An XHTML document can include any number of embedded scripts. The HTML  
 Page 86
Document Object Model(DOM) is the browsers view of an HTML page as an object 
hierarchy, starting with the browser window itself and moving deeper into the page, 
including of the elements on the page and their attribute.
Fig: The HTML DOM
The top level object is window. The document object is a child of window and all the 
objects that appear on the page are descendants of the document object. These objects can 
have children of their own. Eg. Form objects generally have several child objects , 
including textboxes, radio buttons and select menus.
JavaScript and java
Document Forms() Anchors() Images()
Window Text boxes, Radio buttons, check boxes, select lists, txt areas, buttons
DOM allows JS to access and modify the CSS properties and content of any element of a 
displayed XHTML document.
JavaScript and java is only related through syntax. 
JavaScript support for OOP is different from that of Java. 
JavaScript is dynamically typed.
Java is strongly typed language. Types are all known at compile time and operand types 
are checked for compatibility. But variables in JavaScript need not be declared and are 
dynamically typed, making compile time type checking impossible.
Objects in Java are static -> their collection of data number and methods is fixed at  

 Page 87
compile time.
JavaScript objects are dynamic: The number of data members and methods of an object 
can change during execution.
Uses of JavaScript
Goal of JavaScript is to provide programming capability at both server and the client ends 
of a Web connection. Client-side JavaScript is embedded in XHTML documents and is 
interpreted by the browser. This transfer of load from the often overloaded server to the 
normally under loaded client can obviously benefit all other clients. It cannot replace 
server side computations like file operations, database access, and networking.
JavaScript can be used as an alternative to Java applets. Java applets are downloaded 
separately from the XHTML documents that call them but JavaScript are integral part of 
XHTML document, so no secondary downloading is necessary. Java applets far better for 
graphics files scripts.
Interactions with users through form elements, such as buttons and menus, can be 
conveniently described in JavaScript. Because events such as button clicks and mouse 
movements are easily detected with JavaScript they can be used to trigger computations 
and provide feedback to the users.
Eg. When user moves the mouse cursor from a textbox, JavaScript can detect that 
movement and check the appropriateness of the text boxs value. Even without forms, 
user interactions are both possible and simple to program. These interactions which take 
place in dialog windows include getting input from the user and allowing the user to 
make choices through buttons. It is also easy to generate new content in the browser 
display dynamically.
Event driven computation
Event driven computation means that the actions often are executed in response to actions 
often are executed in response to actions of the users of doc, actions like mouse clicks 
and form submissions. This type of computation supports user interactions through 
XHTML form elements on the client display. One of the common uses of JS is client end 
input data validation values entered by users will be checked before sending them to 
server for further processing. This becomes more efficient to perform input data checks 
and carry on this user dialog entirely on the client. This saves both server time and 
internet time. 
 Page 88
Browsers and XHTML/JS documents.
It is an XHTML document does not include embedded scripts, the browser reads the lines 
of the document and renders its window according to the tags, attributes and content it 
finds when a JavaScript script is encountered in the doc, the browser uses its JS 
interpreter to execute the script. When the end of script reached, the browser goes back to 
reading the XHTML document and displaying its content.
JS scripts can appear in either part of an XHTML document, the head or the body, 
depending on the purpose of the script. Scripts that produce content only when requested 
or that react to user interactions are placed in the head of the document. -> Function 
definition and code associated with form elements such as buttons. Scripts that are to be 
interpreted just once, when the interpreter finds them are placed in the document body. 
Accordingly, the interpreter notes the existence of scripts that appear in the head of a 
document, but it does not interpret them while processing the head. Scripts that are found 
in the body of a document are interpreted as they are found.
3.2 Object orientation and Javascript
JavaScript is object based language. It doesnt have classes. Its objects serve both as 
objects and as models of objects. JavaScript does not support class based inheritance as is 
supported in OO language. CTT-Java. But it supports prototype based inheritance i.e a
technique that can be used to simulate some of the aspects of inheritance. JavaScript does 
not support polymorphism. A polymorphic variable can reference related objects of 
different classes within the same class hierarchy. A method call through such a 
polymorphic variable can be dynamically bound to the method in the objects class. 
JavaScript Objects
JavaScript objects are collection of prospectus, which corresponds to the members of
classes in Java & C++. Each property is either a data property or a function or method 
property.
1. Data Properties
a. Primitive Values (Non object Types)
b. Reference to other objects
2. Method Properties ?methods. 
 Page 89
Primitives are non object types and are used as they can be implemented directly in 
hardware resulting in faster operations on their values. These are accessed directly-like 
scalar types in java & C++ called value types. All objects in a JavaScript programs are 
directly accessed through variables. Such a variable is like a reference in java. The 
properties of an object are referenced by attaching the name of the property to the 
variable that references the object. Eg. If myCar variable referencing an object that has 
the property engine, the engine property can be referenced with myCar.engine.
The root object in JavaScript is object. It is ancestor through prototype inheritance, of all 
objects. Object is most generic of all objects, having some methods but no data 
properties. All other objects are specializations of object, and all inherit its methods. 
JavaScript object appears both internally and externally as a list of property/value pairs. 
Properties are names values are data values of functions. All functions are objects and are 
referenced through variables. The collection of properties of JavaScript is dynamic ?
Properties can be added or deleted at any time.
3.3 General syntactic Characteristics
1. JavaScript are embedded either directly or indirectly in XHTML documents.
2. Scripts can appear directly as the content of a <script> tag.
3. The type attribute of <script> must be set to ―text/JavaScript? .
4. The JavaScript can be indirectly embedded in an XHTML document using the src 
attribute of a <script> tag, whose value is name of a file that contains the script.
Eg. <script type=? text/JavaScript? src=? tst_number.js?> </script>
Closing tag is required even if script element has src attribute included.
The indirect method of embedding JavaScript in XHTML has advantages of
1) Hiding the script from the browser user.
2) It also avoids the problem of hiding scripts from older browsers.
3) It is good to separate the computation provided by JavaScript from the layout and 
presentation provided by XHTML and CSS respectively. But it is sometimes not 
convenient and cumbersome to place all JavaScript code in separate file JavaScript 
identifiers or names are similar to programming languages.
1. must begin with (-), or a letter. Subsequent characters may be letters, underscores or 
digits.
2. No length limitations for identifiers. 
 Page 90
3. Case sensitive
4. No uppercase letters.
Reserved words are break delete function return typeof case do if switch var catch else 
in this void continue finally instanceof throw while default for new try with
JavaScript has large collection of predefined words
alert 
open 
java 
self
Comments in JavaScript
// - Single line
/* */ -Multiple line
Two issues regarding embedding JavaScript in XHTML documents.
1) There are some browsers still in use that recognize the <script> tag but do not have JS 
interpreters. These browsers will ignore the contents of the script element and cause no 
problems.
2) There are still a few browsers in use that are so old they do not recognize <script> tag. 
These browsers will display the contents of the script elements as if it were just text. 
Therefore it has been customary to enclose the contents of all script elements in XHTML 
comments to avoid this problem. XHTML validator also has a problem with embedded 
JS. When embedded JS happens to include recognizable tags.
For eg <br/> in output of JS-they often cause validation errors.
Therefore we have to enclose embedded JS in XHTML comments. XHTML comment
introduction (<! - -) works as a hiding prelude to JS code. Syntax for closing a comment 
that encloses JS code is different. It is usual XHTML comment closer but it must be on 
its own line and preceeded by two slashes.
Eg. <!?
-- JS ---
//-->
Many more problem are associated with putting embedded JavaScript in comments in
XHTML document. 
 Page 91
Solution : Put JavaScript scripts of significant style in separate files.
Use of ; in JS is unusual
When EOL coincides with end of statement, the interpreter effectively insects a 
semicolon there, but this leads to problems.
Eg. return x;
Interpreter puts; after return making x an illegal orphan.
Therefore put JS statements on its own line when possible and terminate each statement 
with a semicolon. If stmt does not fit in one line, break the stmt at a place that will ensure 
that the first line does not have the form of a complete statement.
<?xml version = ―1.0 encoding = ―utf-
8? ?>
<!DOCTYPE html PUBLIC ―-//w3c//DTD XHTML
1.1//EN?
http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd>
<! - -hello.html
8
A trivial hello world example of XHTML/JavaScript
- ->
<html xmlns = 
―http://www.w3.org/1999/xhtml? .>
<head>
<title> Hello World</title>
</head>
<body>
<script type =
―text/javascript? >
<!- -
Document.write(―Hello, fellow Web
programmers!? );
//- ->
</script>
</body>
</html> 
 Page 92
3.4 Primitives, operations, and expressions
The primitive data types, operations and expressions of JavaScript.
Primitive Types:
Pure primitive types : Number, String, Boolean, Undefined and null. JavaScript includes 
predefined objects that are closely related to the number, string and Boolean types named 
number, string and Boolean. These are wrapper objects. Each contains a property that 
stores a value of the corresponding primitive type. The purpose of the wrapper object is 
to provide properties and methods that are convenient for use with values of the primitive 
types.
In case of numbers : Properties are more useful. 
In case of string : Methods are more useful.
Because JavaScript coerces values between the number type and number objects and 
between the string type and objects, the methods of number and string can be used on 
variables of the corresponding primitive types.
Difference between primitives and objects :
Prim is a primitive variable with value 17 and obj is a number object whose property 
value is 17. Fig shows how they are stored.
Numeric and String literals:
All numeric literals are values of type number. The numeric values of JavaScript are 
represented internally in double precision floating point form, Numeric values in  
 Page 93
JavaScript are called numbers because of single numeric data type. Literal numbers in a 
script can have forms of either integers or floating point values. Integer literals are strings 
of digits.
Floating point literals can have decimal points or exponents or both. 
Legal numeric literals: 72, 7.2, .72, 72, 7E2, 7e2, .7e2, 7.e2, 7.2E-2.
Integers in Hexadecimal form 0x or 0X.String Literal: Sequence of 0 or more characters 
delimited by either single quotes or double quotes. They can include characters specified 
with escape sequences, such as \n and \t. If you want an actual single quote character in a 
string literal that is delimited by single quotes, embedded single quote must be preceded 
by a backslash.
?You\ re the most freckly person I\ve ever met
―D:\\bookfiles? ->Jo 
embed\
? ?or ――-> Null string
3.5 Screen output and keyboard input
A JavaScript is interpreted when the browser finds the script in the body of the XHTML 
document. Thus the normal screen for the JavaScript is the same as the screen in which 
the content of the host XHTML document is displayed. JS models the XHTML document 
with the document object. The window in which the browser displays an XHTML 
document is modeled with the window object. It includes two properties document and 
window.
Document -> Refers to document object.
Window -> self referential and refers to window object. 
Methods -> write
Write is used to create script o/p, which is dynamically created XHTML document 
content.
Eg. document.write(―The result is : ―, result,? <br/>? );
Because write is used to create XHTML code, the only useful punctuations in its 
parameter is in the form of XHTL tags. Therefore the parameter to write often includes
<br/> writeln methods implementing adds ―\n? to its parameter. As browsers neglects 
line breaks when displaying XHTML, it has no effect on the output. Window objectProgramming the Web 
 Page 94
is JS model for the browser window. It includes three methods that create dialog
boxes for three specific kinds of user interactions. The default object for JS is
window object currently being displayed, so calls to these methods need not include an 
object reference. Alert method opens a dialog window and displays its parameter in that
window. It also displays an OK button. The parameter string to alert is not XHTML
code, it is plain text. There fore the string parameter to alert may include \n but never
should include <br/>. Confirm method opens a dialog window in which it displays its
string parameter, along with two buttons OK and Cancel. Confirm returns a Boolean
value that indicates the users button input
True -> for OK 
False-> for cancel.
Eg. var question = confirm(―Do you want to continue this download?? );
After the user responds to one of the button in the confirm dialog window script can test 
the variable, question and react accordingly. Prompt method creates a dialog window that 
contains a text box which is used to collect a string of input from the user, which prompt 
returns as its value. The window also includes two buttons, OK and Cancel, prompt takes 
two parameters the string that prompts the user for input and a default string in case the 
user does not type a string before pressing one of the two buttons. In many cases an 
empty string is used for the default input.
Eg. name name=prompt(―What is your name? .? ? );
Alert, prompt and confirm cause the browser to wait for a user response. 
Alert ? OK
Prompt-OK, Cancel 
Confirm-OK, Cancel. 
Eg.
<html>
<head>
</title> roots.html</title>
</head>
<body>
<script type =? text/javascript? src=? roots.js? >
</script> 
 Page 95
</body>
</html>
//roots.js
// Compute the real roots of a given quadratic equation. If the roots are imaginary,
//this script displays NaN, because that is what results from taking the square root of
//a negative number.
//Get the coefficients of the equation of the equation from the user 
var a = prompt(―What is the value of ?a?\n? , ―? );
var b = prompt(―What is the value of ?b?\n? , ―? );
var c = prompt(―What is the value of ?c?\n? , ―? );
// Compute Square root
var root_part = Math.sqrt(b * b ? 4.0 * a * c);
var denom = 2.0 * a;
//Compute and Display
Var root1 = (-b + root_part) / denom; Var root2 = (-b -
root_part) / denom; document.write(―The first root is 
:?, root1, ―<br/>? ); document.write(―The second 
root is :?, root2, ―<br/>? );
3.7 Control Statements
Control expression control the order of execution of statements. Compound statements is 
JavaScript are syntactic contains for sequences of statements whose execution they 
control. Compound statement sequence of statements deleted by braces.
Control construct is a control statement whose execution it controls. Compound 
statements are not allowed to create local variables.
Control Expressions.
Control statements flow.
Eg. primitive values, relational expression and compound expressions. Result of 
evaluating a control expression is Boolean value true or false.
For strings. 
true - string 
false-null string 
For numberProgramming the Web 
 Page 96
True- any number
If two operands are not of the same type and operator is neither = = = or ! = =, JS will 
convert to a single type. Eg. If one is string and other is number, JS will convert string to 
a number. If one operand is Boolean and other is not, then Boolean is converted to a
number.(1 for true, 0 for false)
3.7 Object creation and modification
Create objects with the new keyword followed by a constructor. For example, the 
following program creates a TwoDPoint object and prints its fields:
class OriginPrinter {
public static void main(String[] args) {
TwoDPoint origin; // only declares, does not allocate
// The constructor allocates and usually initializes the object 
origin = new TwoDPoint();
// set the fields 
origin.x = 0.0; 
origin.y = 0.0;
// print the two-d point
System.out.println(
"The origin is at " + origin.x + ", " + origin.y);
} // end main
} // end OriginPrinterProgramming the Web 
 Page 97
The ?. is the member access separator.
A constructor invocation with new is required to allocate an object. There is no C++ like 
static allocation.
To compile this class, put it in a file called OriginPrinter.java in the same directory as
TwoDPoint.java and type:
$ javac OriginPrinter.java
Multiple Objects
In general there will be more than one object in any given class. Reference variables are 
used to distinguish between different objects of the same class.
For example, the following program creates two two-d point objects and prints their 
fields:
class TwoPointPrinter {
public static void main(String[] args) {
TwoDPoint origin; // only declares, does not allocate
TwoDPoint one; // only declares, does not allocate
// The constructor allocates and usually initializes the object
origin = new TwoDPoint();
one = new TwoDPoint();
// set the fields 
origin.x = 0.0; 
origin.y = 0.0; 
one.x = 1.0; 
one.y = 0.0;
// print the 2D points
System.out.println(
"The origin is at " + origin.x + ", " + origin.y); 
System.out.println("One is at " + one.x + ", " + one.y);
} // end main
} // end TwoPointPrinterProgramming the Web 
 Page 98
one and origin are two different reference variables pointing to two different point 
objects. It's not enough to identify a variable as a member of a class like x or y in the 
example above. You have to specify which object in the class you're referring to.
It is possible for two different reference variables to point to the same object.
When an object is no longer pointed to by any reference variable (including references 
stored deep inside the runtime or class library) it will be marked for garbage collection.
For example, the following program declares two TwoDPoint reference variables, creates 
one two-d point object, and assigns that object to both variables. The two variables are 
equal.
class EqualPointPrinter {
public static void main(String[] args) {
TwoDPoint origin1; // only declares, does not allocate
TwoDPoint origin2; // only declares, does not allocate
// The constructor allocates and usually initializes the object 
origin1 = new TwoDPoint();
origin2 = origin1;
// set the fields 
origin1.x = 0.0; 
origin1.y = 0.0;
// print
System.out.println(
"origin1 is at " + origin1.x + ", " + origin1.y); 
System.out.println(
"origin2 is at " + origin2.x + ", " + origin2.y);
} // end main
} // end EqualPointPrinter
origin1 and origin2 are two different reference variables referring to the same point 
object.
3.8 ArraysProgramming the Web 
 Page 99
An array is a collection of variables of the same type. The args[] array of a main() method 
is an array of Strings.
Consider a class which counts the occurrences of the digits 0-9. For example you might 
wish to test the randomness of a random number generator. If a random number generator 
is truly random, all digits should occur with equal frequency over a sufficiently long 
period of time.
You will do this by creating an array of ten ints called ndigit. The zeroth component of 
ndigit will track the number of zeros; the first component will track the numbers of ones 
and so forth. The RandomTest program below tests Java's random number generator to 
see if it produces apparently random numbers.
import java.util.Random;
class RandomTest {
public static void main (String args[]) {
int[] ndigits = new int[10];
Random myRandom = new Random();
// Initialize the array
for (int i = 0; i < 10; i++) {
ndigits[i] = 0;
}
// Test the random number generator a whole lot 
for (long i=0; i < 100000; i++) {
// generate a new random number between 0 and 9 
double x = myRandom.nextDouble() * 10.0;
int n = (int) x;
//count the digits in the random number 
ndigits[n]++;
}
// Print the results
for (int i = 0; i < 10; i++) { 
System.out.println(i+": " + ndigits[i]);
 Page 100
}
}
Below is one possible output from this program. If you run it your results should be 
slightly different. After all this is supposed to be random. These results are pretty much 
what you would expect from a reasonably random generator. If you have a fast CPU and 
some time to spare, try bringing the number of tests up to a billion or so, and see if the 
counts for the different digits get any closer to each other.
$ javac RandomTest.java
$ java RandomTest
0: 10171
1: 9724
2: 9966
3: 10065
4: 9989
5: 10132
6: 10001
7: 10158
8: 9887
9: 9907
There are three for loops in this program, one to initialize the array, one to perform the 
desired calculation, and a final one to print out the results. This is quite common in code 
that uses arrays.
3.9 Functions
Methods say what an object does. 
class TwoDPoint {
double x;
double y;
void print() {
System.out.println(this.x + "," + this.y);
 Page 101
}
Notice that you use the Java keyword this to reference a field from inside the same class. 
TwoDPoint origin = new TwoDPoint();
origin.x = 0.0; 
origin.y = 0.0; 
origin.print();
noun-verb instead of verb-noun; that is subject-verb instead of verb-direct object. 
subject-verb-direct object(s) is also possible.
3.10 Constructor
Constructors create new instances of a class, that is objects. Constructors are special 
methods that have the same name as their class and no return type. For example,
class TwoDPoint {
double x;
double y;
TwoDPoint(double xvalue, double yvalue) {
this.x = xvalue;
this.y = yvalue;
}
String getAsString() {
return "(" + this.x + "," + this.y + ")";
}
void setX(double value) {
this.x = value;
}
void setY(double value) {
this.y = value;
}
double getX() { 
 Page 102
return this.x;
}
double getY() {
return this.y;
}
}
Constructors are used along with the new keyword to produce an object in the class (also 
called an instance of the class):
TwoDPoint origin = new TwoDPoint(0.0, 0.0); 
System.out.println("The x coordinate is " + origin.getX());
3.11 Errors in scripts
Web browsers are such an hostile environment that it is almost guaranteed that we will 
constantly deal with runtime errors. Users provide invalid input in ways you didn't think 
of. New browser versions change their behavior. An AJAX call fails for a number of 
reasons.
Many times we can't prevent runtime errors from happening, but at least we can deal with 
them in a manner that makes the user experience less traumatic.
Completely unhandled errors
Look at this seemingly trivial code snippet. 
function getInput() {
var name = window.prompt('Type your name', '');
alert('Your name has ' + name.length + ' letters.');
}
It may not be obvious, but this code has a bug waiting to break free. If the user clicks 
Cancel or presses Esc the prompt() function will return null, which will cause the next 
line to fail with a null reference error.
If you as a programmer don't take any step to deal with this error, it will simply be 
delivered directly to the end user, in the form of a utterly useless browser error message 
like the one below. 
 Page 103
Depending on the user's browser or settings, the error message may be suppressed and 
only an inconspicuous icon shows up in the status bar. This can be worse than the error 
message, leaving the users thinking the application is unresponsive.
Globally handled errors
The window object has an event called onerror that is invoked whenever there's an 
unhandled error on the page.
window.onerror = function (message, url, lineNo) {
alert(
'Error: ' + message +
'\n Url: ' + url +
'\n Line Number: ' + lineNo);
return true;
}
As you can see, the event will pass 3 arguments to the invoked function. The first one is 
the actual error message. The second one is the URL of the file containing the error 
(useful if the error is in an external .js file.) The last argument is the line number in that 
file where the error happened.
Returning true tells the browser that you have taken care of the problem. If you return 
false instead, the browser will proceed to treat the error as unhandled, showing the error 
message and the status bar icon.
Here's the message box that we will be showing to the user.
Structured Error Handling
The best way to deal with errors is to detect them the closest possible to where they 
happen. This will increase the chances that we know what to do with the error. To that 
effect JavaScript implements structured error handling, via the try...catch...finally block, 
also present in many other languages.
Syntax 
try { 
 Page 104
statements;
} catch (error) {
statements;
} finally {
statements;
}
The idea is simple. If anything goes wrong in the statements that are inside the try block's 
statements then the statements in the catch block will be executed and the error will be 
passed in the error variable. The finally block is optional and, if present, is always 
executed last, regardless if there was an error caught or not.
Let's fix our example to catch that error.
function getInput(){
try {
var name = window.prompt('Type your name', '');
alert('Your name has ' + name.length + ' letters.');
} catch (error) {
alert('The error was: ' + error.name +
'\n The error message was: ' + error.message);
} finally {
//do cleanup
}
}
The error object has two important properties: name and message. The message property 
contains the same error message that we have seen before. The name property contains 
the kind of error that happened and we can use that to decide if we know what to do with 
that error.
It's a good programming practice to only handle the error on the spot if you are certain of 
what it is and if you actually have a way to take care of it (other than just suppressing it 
altogether.) To better target our error handling code, we will change it to only handle 
errors named "TypeError", which is the error name that we have identified for this bug. 
 Page 105
function getInput(){
try {
var name = window.prompt('Type your name', '');
alert('Your name has ' + name.length + ' letters.');
} catch (error) {
if (error.name == 'TypeError') {
alert('Please try again.');
} else {
throw error;
}
} finally {
//do cleanup
}
}
Now if a different error happens, which is admittedly unlikely in this simple example, 
that error will not be handled. The throw statement will forward the error as if we never 
had this try...catch...finally block. It is said that the error will bubble up.
Throwing custom errors
We can use the throw statement to throw our own types of errors. The only 
recommendation is that our error object also has a name and message properties to be 
consistent in error handling.
throw {
name: 'InvalidColorError',
message: 'The given color is not a valid color value.'
};
Debugging
One of the most important activities in software development is debugging. It can also be 
one of the most costly. That's why we need to do our best to reduce the amount of time 
spent in debugging.
One way to reduce this time is to create automated unit tests, which we will see in theProgramming the Web 
 Page 106
lesson Production Grade JavaScript.
Another way is to use the best tools available and try to remove the pain associated with 
debugging. It used to be the case that debugging tools for JavaScript were archaic or 
close to non-existent. This situation has improved a lot and now we can confidently say 
we have feasible ways to debug JavaScript without resorting to horrendous tactics, such 
as sprinkling alert() calls across our code.
We won't waste your time discussing all the existing tools for debugging. Instead we will 
focus on the tool that singlehandedly re-wrote the JavaScript debugging history.

Editors




You might like this video:Watch more here

Watch more videos from this user Here

Learn how to upload a video and start earning here