0% found this document useful (0 votes)
18K views

Java Script

The document provides an overview of JavaScript including what it is, why it is used, what it can do, syntax, terminology, data types, objects, arrays, functions and operators. JavaScript is an interpreted scripting language that is commonly used to make web pages interactive.

Uploaded by

Joyce Ann Nunez
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18K views

Java Script

The document provides an overview of JavaScript including what it is, why it is used, what it can do, syntax, terminology, data types, objects, arrays, functions and operators. JavaScript is an interpreted scripting language that is commonly used to make web pages interactive.

Uploaded by

Joyce Ann Nunez
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 83

JavaScript Basics

What is JavaScript?

CIS 233
Why Use JavaScript?

• JavaScript enhances Web pages with dynamic and


interactive features.

• JavaScript is a scripting language most often used for


client-side web development.

• Initiated by Netscape and called LiveScript.

• Scripting language (object-oriented)


• Lightweight programming language developed by
Netscape
• Interpreted, not compiled
CIS 233
What Can JavaScript Do?
• To create interactive user interface in a web
page (e.g., menu, pop-up alert, windows, etc.)

• Manipulating web content dynamically


• Change the content and style of an element
• Replace images on a page without page reload
• Hide/Show contents

• Generate HTML contents on the fly

• Form validation

• AJAX (e.g. Google complete)


CIS 233
What Can JavaScript Do?

• Common JavaScript tasks can replace server-


side scripting.

• JavaScript enables shopping carts, form


validation, calculations, special graphic and
text effects, image swapping, image mapping,
clocks, and more.

CIS 233
JavaScript Versus Java

• JavaScript is interpreted while Java is


compiled
• But server-side JavaScript is compiled

• JavaScript is object-based while Java is object-


oriented
• Object-based languages can utilize pre-defined
objects, but you are limited in terms of creating your
own objects

CIS 233
JavaScript Versus Java

• JavaScript has loose data typing, while Java


has strong data typing
• Loose data typing means that a variable can hold
any kind of data

• JavaScript code is embedded in an HTML


document while Java applets are stand-alone
applications that can be accessed from HTML

CIS 233
JavaScript Versus Java

• JavaScript has dynamic binding, while Java


has static binding
• Names bound at runtime

• JavaScript can access browser objects and


functionality, while Java cannot

CIS 233
JavaScript Syntax.

• Unlike HTML, JavaScript is case sensitive.

• Dot Syntax is used to combine terms.


• e.g., document.write("Hello World")

• Certain characters and terms are reserved.

• JavaScript is simple text (ASCII).

CIS 233
JavaScript Terminology.

• JavaScript programming uses specialized


terminology.

• Understanding JavaScript terms is


fundamental to understanding the script.
• Objects, Properties, Methods, Events, Functions,
Values, Variables, Expressions, Operators.

CIS 233
Objects

• Objects refers to windows, documents, images,


tables, forms, buttons or links, etc.

• Objects should be named.

• Objects have properties that act as modifiers.

CIS 233
Properties

• Properties are object attributes.

• Object properties are defined by using the


object's name, a period, and the property
name.
• e.g., background color is expressed by:
document.bgcolor .
• document is the object.
• bgcolor is the property.

CIS 233
Methods

• Methods are actions applied to particular


objects. Methods are what objects can do.
• e.g., document.write(”Hello World")
• document is the object.
• write is the method.

CIS 233
Events

• Events associate an object with an action.


• e.g., the OnMouseover event handler action can
change an image.
• e.g., the onSubmit event handler sends a form.

• User actions trigger events.

CIS 233
Functions

• Functions are named statements that performs


tasks.
• e.g., function doWhatever () {statement here}
• The curly braces contain the statements of the
function.

• JavaScript has built-in functions, and you can


write your own.

CIS 233
Values

• Values are bits of information.

• Values types and some examples include:


• Number: 1, 2, 3, etc.
• String: characters enclosed in quotes.
• Boolean: true or false.
• Object: image, form
• Function: validate, doWhatever

CIS 233
Variables

• Must declare variables before they’re used in the program


• Declare at the top of the program & terminate each
statement with ‘;’
• Intialize variables when appropriate
• Local variables (declared within a function) destroyed
after function exit.
 Can only be accessed within the function

• Variables are created by declaration using the var


command with or without an initial value state.
• e.g. var month;
• e.g. var month = April;

CIS 233
Data Types
• Primitive data types
• Number: integer & floating-point numbers
• Boolean: true or false
• String: a sequence of alphanumeric characters

• Composite data types (or Complex data types)


• Object: a named collection of data
• Array: a sequence of values (an array is actually a predefined
object)

• Special data types


• Null: the only value is "null" – to represent nothing.
• Undefined: the only value is "undefined" – to represent the value
of an unintialized variable CIS 233
Strings

• A string variable can store a sequence of


alphanumeric characters, spaces and special
characters.

• Each character is represented using 16 bit


• You can store Chinese characters in a string.

• A string can be enclosed by a pair of single quotes


(') or double quote (").

• Use escaped character sequence to represent


special character (e.g.: \", \n, \t)
CIS 233
Object

• An object is a collection of properties.

• Properties can be variables (Fields) or Functions


(Methods)

• There is no "Class" in JavaScript.

CIS 233
var obj = new Object(); // Creating an object

// Adding three properties to obj


obj.prop1 = 123;
obj.prop2 = "456";
obj["prop3"] = true; // same as obj.prop3 = true

var keys = "", values = "";


for (var p in obj) {
keys += p + " ";
values += obj[p] + " ";
}

alert(keys);
// Show "prop1 prop2 pro3 "

alert(values);
// Show "123 456 true "

Example: Using for … in loop with object


CIS 233
Array

• An array is represented by the Array object. To


create an array of N elements, you can write
var myArray = new Array(N);

• Index of array runs from 0 to N-1.

• Can store values of different types

• Property "length" tells the # of elements in the


array.

• Consists of various methods to manipulate its


elements. e.g., reverse(), push(), concat(),CIS 233
Array= "Ford";
Examples
var Car = new Array(3);
Car[0]
Car[1] = "Toyota";
Car[2] = "Honda";

// Create an array of three elements with initial


// values
var Car2 = new Array("Ford", "Toyota", "Honda");

// Create an array of three elements with initial


// values
var Car3 = ["Ford", "Toyota", "Honda"];

CIS 233
// An array of 3 elements, each element is undefined
var tmp1 = new Array(3);

// An array of 3 elements with initial values


var tmp2 = new Array(10, 100, -3);

// An array of 3 elements with initial values


// of different types
var tmp3 = new Array(1, "a", true);

// Makes tmp3 an array of 10 elements


tmp3.length = 10; // tmp[3] to tmp[9] are undefined.

// Makes tmp3 an array of 100 elements


tmp3[99] = "Something";
// tmp[3] to tmp[98] are undefined.

CIS 233
Null & Undefined

• An undefined value is represented by the


keyword "undefined".
• It represents the value of an uninitialized variable

• The keyword "null" is used to represent


“nothing”
• Declare and define a variable as “null” if you want the
variable to hold nothing.
• Avoid leaving a variable undefined.

CIS 233
Type Conversion (To Boolean)

• The following values are treated as false


• null
• undefined
• +0, -0, NaN (numbers)
• "" (empty string)

CIS 233
Type Conversion

• Converting a value to a number


var numberVar = someVariable – 0;

• Converting a value to a string


var stringVar = someVariable + "";

• Converting a value to a boolean


var boolVar = !!someVariable;

CIS 233
Expressions

• Expressions are commands that assign


values to variables.

• Expressions always use an assignment


operator, such as the equals sign.
• e.g., var month = May; is an expression.

• Expressions end with a semicolon.

CIS 233
Operators

• Operators are used to handle variables.

• Types of operators with examples:


• Arithmetic operators, such as plus.
• Comparisons operators, such as equals.
• Logical operators, such as and.
• Control operators, such as if.
• Assignment and String operators.

CIS 233
Methods of Using JavaScript.

1. JavaScripts can reside in a separate page.

2. JavaScript can be embedded in HTML


documents -- in the <head>, in the
<body>, or in both.

3. JavaScript object attributes can be placed


in HTML element tags.
e.g., <body onLoad="alert('WELCOME')">

CIS 233
1. Using Separate JavaScript Files.

• Linking can be advantageous if many pages use


the same script.

• Use the source element to link to the script file.

<script src="myjavascript.js”
language="JavaScript1.2”
type="text/javascript">
</script>

CIS 233
2. Embedding JavaScript in HTML.

• When specifying a script only the tags


<script> and </script> are essential, but
complete specification is recommended:

<script language="javascript”
type="text/javascript">
<!-- Begin hiding
window.location=”index.html"
// End hiding script-->
</script>

CIS 233
Using Comment Tags

• HTML comment tags should bracket any script.

• The <!-- script here --> tags hide scripts


in HTML and prevent scripts from displaying in
browsers that do not interpret JavaScript.

• Double slashes // are the signal characters


for a JavaScript single-line comment.

CIS 233
3. Using JavaScript in HTML Tags.

• Event handlers like onMouseover are a perfect


example of an easy to add tag script.

<a href=”index.html”
onMouseover="document.logo.src='js2.gif'"
onMouseout="document.logo.src='js.gif'">
<img src="js.gif" name="logo">
</a>

CIS 233
Creating an Alert Message

• The following script in the <body> tag uses the


onLoad event to display an Alert window

• The message is specified within parenthesis.

<body onLoad="alert('WELCOME. Enjoy


your visit. Your feedback can improve
cyberspace. Please let me know if you
detect any problems. Thank you.')">

CIS 233
Conditional Statements

• “if” statement

• “if … else” statement

• "? :" ternary conditional statement

• “switch” statement
• The syntax of these statements are similar to those
found in C and Java.

CIS 233
Looping Statement

• “for” Loops

• “for/in” Loops

• “while” Loops

• “do … while” Loops

• “break” statement

• “continue” statement

• All except "for/in" loop statements have the same syntax as those
found in C and Java.

CIS 233
“for/in” statement
for (var variable in object) {
statements;
}

• To iterate through all the properties in "object".

• "variable" takes the name of each property in


"object“

• Can be used to iterate all the elements in an


Array object.

CIS 233
var keys = "", values = "";
var mylist = new Array("Chinese", "English", "Jap");
mylist.newField1 = "Something";

for (var key in booklist) {


keys += key + " ";
values += booklist[counter] + " ";
}

// keys becomes "0 1 2 newField1"


// values becomes "Chinese English Jap Something"

CIS 233
Functions

• Abstraction
• Experience has taught us that much code is duplicated
throughout program
• Functions let us write the functionality once, then reuse it

• Encapsulation
• Functions encapsulate a specific capability or
feature
• Function name allows us to access a function in our
program

CIS 233
Function

• Parameterization
• We can customize the function’s result by
passing in different values each time we use it

CIS 233
Function Used

• Reasons to use functions


• Ease of communication
• Problem simplification
• Easier construction
• Code readability
• Reusability
• Maintainability

• In JS, functions are the primary encapsulation


mechanism

CIS 233
Function Issues

• Key issues about using functions


• Naming functions
• Passing in parameters
• Using local variables within functions
• How to call (i.e., invoke) functions
• How to handle a function’s return value
• Where to put JS functions in your webpage

CIS 233
JavaScript Functions – Naming
• Function names
• Name describes what function does
• Name is an identifier, so follow JS identifier
syntax rules & course coding standards

• Example
findMaxValue(‘put some parameters here’)

CIS 233
JavaScript Functions -- Parameters
• Passing parameters to the function
• Parameters provide functions with input
• Implicitly declared variables that can be accessed by
code within function body
• You provide actual input values when you call the
function
• Parameters are named variables separated by commas

• Example,
function findMaxValue(num1, num2, num3)

CIS 233
JavaScript Functions – Where to put?
• Put functions within <script>….</script> tags within the
<head> section of the web page

<head>

<script language=“JavaScript”>

declare functions here….

</script>

</head>

CIS 233
JavaScript Functions – Local Variables
• If needed, you can declare local variables within a
function

• local variable is visible only within the function body


after it’s declared

• Commonly used to store results of an intermediate


calculation

CIS 233
JavaScript Functions – Local
Variables
function findMaxValue(num1, num2,num3) {
var tempMax; //local var

if (num1 >= num2) {


tempMax = num1;
}

else {
tempMax = num2;
}

if(num3 >= tempMax) {


tempMax = num3;
}

return tempMax;

} //end function

CIS 233
JavaScript Functions -- Calling
• To call a function from your program, add a statement
that contains the function name with values for the
parameters the function requires

• Example…somewhere in the <body>….,

var x = 1, y = 4, z = 2;

findMaxValue(x, y, z);

• What value does the function return?

• What happens with the result?

CIS 233
JavaScript Functions -- Return
• Return keyword tells function to return some
value and exit immediately

• Function can have multiple return statements


but only 1 can be executed in any given
function call

• Normally used to return the final result of a


calculation to the calling program

• For an example, see findMaxValue function

CIS 233
JavaScript Functions -- Return
• Good Example
• Uses var maxNumber in calling program
• Function’s return value is assigned to maxNumber
• Display of maxNumber has correct value for inputs

• Code snippet

var x = 1, y = 4, z = 2;
var maxNumber = findMaxNumber(x, y, z);
document.write(“The maximum is: “ + maxNumber);

CIS 233
JavaScript Functions -- Return
• The return must be handled properly or it will be ‘lost’

• Usually, you want to assign the result of a function to


a variable

• Bad Example1,
• Declares var maxNumber in calling program, then
displays it
• Value is ‘undefined’ because maxNumber is never
initialized & the return value is never assigned to it

CIS 233
JavaScript Functions -- Return
• Bad Example 2
• Declares var tempMax in calling program
because that’s the name of the var being
returned from function
• Attempts to display tempMax but value is
undefined
• the tempMax in calling program may have the
same name as var being ‘returned’ but they are
different variables!

CIS 233
JavaScript Functions – Parameter
Sequence
• When calling functions, must enter parameters in same order as
specified in function argument list.

1. function calculateDensity(height, width, depth, mass){

2. var volume = height * width * depth;

3. var density = mass / volume;

4. return density;

5. }

6. ……………………………………………….

7. var hth = 2, wth = 3, dth = 4, mass = 10;

8. var result = calculateDensity(2, 10, 3, 4);

9. //returns .07 but correct answer is .42!!!

CIS 233
JavaScript Functions – Global
Variables
• Global variables are those declared outside of
functions

• Global variables are ‘visible’ from anywhere in the


program, including inside functions
var globalHello = “Hello!”;

function writeHello() {

document.write(globalHello);

// outputs “Hello!”

CIS 233
JavaScript Functions – Testing

• Test each function thoroughly before proceeding


with next programming task

• Using multiple sets of inputs, be sure to test all


possible outcomes

• For each test, be sure calling program is properly


handling return values

CIS 233
JavaScript Functions – Debugging

• Use diagnostic output statements to trace program execution

• Good places for diagnostic outputs


• Just before entering function
• Immediately upon entering function
• Before/In/After complex logic or computation
• Just before function return statement
• Immediately after function returns to calling program

CIS 233
JavaScript Functions

• Built-In Functions
• Prompt
• Alert
• Confirm

CIS 233
alert(), confirm(), and prompt()
<script type="text/javascript">
alert("This is an Alert method");
confirm("Are you OK?");
prompt("What is your name?");
prompt("How old are you?","20");
</script>

CIS 233
JavaScript and HTML Forms

• Object Model for the Browser Window


• Compound object structure is created when a web
page loads into a browser
 Hierarchy
• Window is an object, the HTML document is an
object and its elements are objects
• These objects have primitives associated with them

CIS 233
JavaScript and HTML Forms

• window [closed, location]

 history [length]

 document [bgColor, fgColor, URL,


lastmodified,linkColor, vlinkColor]
– images [properties]
– links [properties]
– frames [properties]
– forms [properties]

CIS 233
JavaScript and HTML Forms

• Window object is parent of structure


• window.closed is primitive that is Boolean
• window.location primitive contains string of the URL of the
HTML file
• window.document object is primary focus

• When web page is loaded the HTML elements assign values to


most of these window.document primitives

• Often the word window is excluded as in document.write but


need it if referring to multiple open windows

• Properties can also be objects

CIS 233
JavaScript and HTML Forms

• Methods
• Behavior associated with an object
• Essentially functions that perform an action
• Some are built in and others user made

• Built-In Methods of the window object


• Confirm
• Alert
• Prompt

CIS 233
JavaScript and HTML Forms

• User Events
• An event occurs when a user makes a change to a
form element
 Ex. Click a button, mouseover an image
• Detection of an event done by event handlers
• Event handler is an attribute of the HTML button
• <form>
 <input type=button value=“please click”
onclick=“function name()”>
• </form>

CIS 233
JavaScript and HTML Forms

<HTML>

<HEAD>

<SCRIPT LANGUAGE=JavaScript><!--

function changecolor(){

document.bgColor="#ff0000";

//--></SCRIPT>

</HEAD>

<BODY>

<P><FORM >

<P><INPUT TYPE=button VALUE="Click Me" onclick="changecolor()">

</FORM>

</BODY>

</HTML>

CIS 233
JavaScript and HTML Forms

• Form Object
• Window.document.form
• A form is a property of the document but is also an
object
• Form elements are properties of a form and are also
objects
• Access to form’s properties is done through the
NAME attribute of the FORM tag
• Access to the properties of the form elements is
done through the NAME attributes of the particular
form element

CIS 233
JavaScript and HTML Forms

Interactive Programming on the Internet ,Knuckles


CIS 233
JavaScript and HTML Forms
<HTML>

<HEAD>

<SCRIPT LANGUAGE=JavaScript><!--

function plus(){

var n1; //--></SCRIPT>


var n2;
</HEAD>
n1=document.addmult.num1.value;

n2=document.addmult.num2.value; <BODY BGCOLOR="#FFFFCC">

n1=parseFloat(n1);
<P><FORM name=addmult>
n2=parseFloat(n2);
<P>Enter a number in each field:

document.addmult.result.value=n1+n2; <INPUT TYPE=text NAME=num1 VALUE="" SIZE=5>


}
<INPUT TYPE=text NAME=num2 VALUE=""
function times(){
SIZE=5><BR>
var n1;

var n2; <INPUT TYPE=button VALUE="+" onclick="plus()">


n1=document.addmult.num1.value;
<INPUT TYPE=button VALUE="*"
n2=document.addmult.num2.value; onclick="times()"><BR>

n1=parseFloat(n1);
<INPUT TYPE=reset VALUE="Reset Form"><BR>
n2=parseFloat(n2);
<TEXTAREA NAME=result ROWS=3 COLS=27
document.addmult.result.value=n1*n2; WRAP=virtual></TEXTAREA>
}
</FORM>

</BODY>

</HTML>

CIS 233
JavaScript and HTML Forms
Form for submitting info for server side
processing

Interactive Programming on the Internet


,Knuckles
CIS 233
JavaScript and HTML Forms

• <HTML> • <TR>

• <TD WIDTH=83>
• <HEAD>
• <P>Address:
• <SCRIPT LANGUAGE=JavaScript><!-- • </TD>

• function verify(){ • <TD>

• <P><INPUT TYPE=text NAME=address VALUE="" SIZE=32>


• with(document.infoform){
• </TD>
• if((fullname.value=="")||(address.value=="")||(email.value=="")){
• </TR>
• alert("You have left one or more fields blank. Please supply the • <TR>
necessary information, and re-submit the form.");
• <TD WIDTH=83>
• } • <P>E-mail:

• else { • </TD>

• <TD>
• display.value="The following information has been added to our
guestbook:\r"+fullname.value+"\r"+ address.value +"\r" +email.value; • <P><INPUT TYPE=text NAME=email VALUE="" SIZE=32>

• } • </TD>

• </TR>
• }
• <TR>
• } • <TD WIDTH=83>

• //--></SCRIPT> • <P><INPUT TYPE=button VALUE="Submit" onclick="verify()">

• </TD>
• </HEAD>
• <TD>
• <BODY BGCOLOR="#FFFFCC">
• <P><INPUT TYPE=reset VALUE="Clear Your Information">
• <P><FORM name=infoform> • </TD>

• <P><TABLE BORDER=0> • </TR>

• <TR>
• <TR>
• <TD COLSPAN=2>
• <TD WIDTH=83> • <P><TEXTAREA NAME=display ROWS=5 COLS=41 WRAP=virtual></TEXTAREA>

• <P>Name: • </TD>

• </TR>
• </TD>
• </TABLE>
• <TD>

• <P><INPUT TYPE=text NAME=fullname VALUE="" SIZE=32> • </FORM>

• </TD> • </BODY>

• </HTML>
• </TR>

CIS 233
Event Handlers

• Event Handler – a segment of codes (usually a


function) to be executed when an event occurs

• We can specify event handlers as attributes in the


HTML tags.

• The attribute names typically take the form


"onXXX" where XXX is the event name.
e.g.:

<a href="…" onClick="alert('Bye')">Other


Website</a> CIS 233
Event Handlers
Event Handlers Triggered when
onChange The value of the text field, textarea, or a drop down list
is modified
onClick A link, an image or a form element is clicked once
onDblClick The element is double-clicked
onMouseDown The user presses the mouse button
onLoad A document or an image is loaded
onSubmit A user submits a form
onReset The form is reset
onUnLoad The user closes a document or a frame
onResize A form is resized by the user

For a complete list, see


http://www.w3schools.com/htmldom/dom_obj_event.asp
CIS 233
onClick Event Handler Example
<html>
<head>
<title>onClick Event Handler Example</title>
<script type="text/javascript">
function warnUser() {
return confirm("Are you a student?”);
}
</script>
</head>
<body>
<a href="ref.html" onClick="return warnUser()">
<!--
If onClick event handler returns false, the link
is not followed.
-->
Students access only</a>
</body>
</html>
CIS 233
onLoad Event Handler Example
<html><head>
<title>onLoad and onUnload Event Handler Example</title>
</head>
<body
onLoad="alert('Welcome to this page')"
onUnload="alert('Thanks for visiting this page')"
>
Load and UnLoad event test.
</body>
</html>

CIS 233
onMouseOver & onMouseOut
Event Handler
<html>
<head>
<title>onMouseOver / onMouseOut Event Handler Demo</title>
</head>
<body>
<a href="http://www.cuhk.edu.hk"
onMouseOver="window.status='CUHK Home'; return true;"
onMouseOut="status=''"
>CUHK</a>
</body>
</html>
• When the mouse cursor is over the link, the browser displays the text "CUHK
Home" instead of the URL.
• The "return true;" of onMouseOver forces browser not to display the URL.
• window.status and window.defaultStatus are disabled in Firefox.
CIS 233
onSubmit Event Handler
<html><head>
<title>onSubmit Event Handler Example</title>
<script type="text/javascript">
function validate() {
// If everything is ok, return true
// Otherwise return false
}
</script>
</head>
<body>
<form action="MessageBoard" method="POST"
onSubmit="return validate();"
>

</form></body></html>

• If onSubmit event handler returns false, data is not submitted.


• If onReset event handler returns false, form is not reset CIS 233
Build-In JavaScript Objects
Object Description
Array Creates new array objects
Boolean Creates new Boolean objects
Date Retrieves and manipulates dates and times
Error Returns run-time error information
Function Creates new function objects
Math Contains methods and properties for performing mathematical
calculations
Number Contains methods and properties for manipulating numbers.
String Contains methods and properties for manipulating text strings

• See online references for complete list of available methods in these objects:
http://javascript-reference.info/
CIS 233
String Object (Some useful methods)
• length
•A string property that tells the number of character in the string

• charAt(idx)
•Returns the character at location "idx"

• toUpperCase(), toLowerCase()
•Returns the same string with all uppercase/lowercase letters

• substring(beginIdx)
•Returns a substring started at location "beginIdx"

• substring(beginIdx, endIdx)
•Returns a substring started at "beginIdx" until "endIdx" (but not including
"endIdx"

• indexOf(str)
•Returns the position where "str" first occurs in the string
CIS 233
Error and Exception Handling in
JavaScript
• Javascript makes no distinction between Error and
Exception (Unlike Java)

• Handling Exceptions
• The onError event handler
 A method associated with the window object.
 It is called whenever an exception occurs

• The try … catch … finally block


 Similar to Java try … catch … finally block
 For handling exceptions in a code segment

• Use throw statement to throw an exception


 You can throw value of any type

• The Error object


 Default object for representing an exception
 Each Error object has a name and message properties
CIS 233
How to use “onError” event handler?
<html>
<head>
<title>onerror event handler example</title>
<script type="text/javascript">
function errorHandler(){
alert("Error Ourred!");
}
// JavaScript is casesensitive
// Don't write onerror!
window.onError = errorHandler;
</script>
</head>
<body>
<script type="text/javascript">
document.write("Hello there;
</script>
</body>
</html> CIS 233
try … catch … finally
try {
// Contains normal codes that might throw an exception.

// If an exception is thrown, immediately go to


// catch block.

} catch ( errorVariable ) {
// Codes here get executed if an exception is thrown
// in the try block.

// The errorVariable is an Error object.

} finally {
// Executed after the catch or try block finish

// Codes in finally block are always executed


}
// One or both of catch and finally blocks must accompany the try
block. CIS 233
try … catch … finally example
<script type="text/javascript">
try{
document.write("Try block begins<br>");
// create a syntax error
eval ("10 + * 5");

} catch( errVar ) {
document.write("Exception caught<br>");
// errVar is an Error object
// All Error objects have a name and message properties
document.write("Error name: " + errVar.name + "<br>");
document.write("Error message: " + errVar.message +
"<br>");
} finally {
document.write("Finally block reached!");
}
</script>
CIS 233
Throwing Exception
<script type="text/javascript">
try{
var num = prompt("Enter a number (1-2):", "1");
// You can throw exception of any type
if (num == "1")
throw "Some Error Message";
else
if (num == "2")
throw 123;
else
throw new Error ("Invalid input");
} catch( err ) {
alert(typeof(errMsg) + "\n" + err);
// instanceof operator checks if err is an Error object
if (err instanceof Error)
alert("Error Message: " + err.message);
}
</script> CIS 233
• Return to jqjacobs.net/web -- JavaScript Basics

References and Recommended Readings

The Web Wizard’s Guide to JavaScript by Steven Estrella

JavaScript for the World Wide Web by Tom Negrino and Dori Smith

©2003 by James Q. Jacobs. All rights reserved.


My photography, graphics, and writings may be used and reproduced for
non-commercial, educational purposes, such as classroom materials,
without my permission if you cite the source in some way.

CIS 233

You might also like