Вы находитесь на странице: 1из 64

The JavaScript Language

CS 312: Internet programming and


applications

1
(CIVE)
Objectives
• Learn about JavaScript
• Using JavaScript in HTML
• Language Elements
• Variables
• Operators
• Control Statements
• Functions
• Objects
• Exception handling.

2
About JavaScript
• JavaScript is not Java, or even related to Java
• The original name for JavaScript was “LiveScript”
• The name was changed when Java became popular
• Statements in JavaScript resemble statements in Java,
because both languages borrowed heavily from the C
language
• JavaScript should be fairly easy for Java programmers to learn
• However, JavaScript is a complete, full-featured, complex language
• JavaScript is seldom used to write complete “programs”
• Instead, small bits of JavaScript are used to add functionality to HTML
pages
• JavaScript is usually embedded directly into HTML pages
3
About JavaScript
• JavaScript was designed to add interactivity to HTML
pages
• JavaScript is a scripting language (a scripting language is
a lightweight programming language)
• A JavaScript consists of lines of executable computer
code
• JavaScript is an interpreted language (means that scripts
execute without preliminary compilation)
• Everyone can use JavaScript without purchasing a license

4
Why use JavaScript?
• To add dynamic function to your HTML.
– JavaScript does things that HTML can’t—like logic.
– You can change HTML on the fly.
• To remove some of the form-processing burden.
– JavaScript runs in the browser, not on the Web server.
• Better performance
– JavaScript can validate the data that users enter into the form,
before it is sent to your Web application.

5
When not to use JavaScript
• When you need to access other resources.
– Files
– Programs
– Databases

• When you are using sensitive or copyrighted data or


algorithms.
– Your JavaScript code is open to the public.

6
Using JavaScript in a browser
• JavaScript code is included within <script> tags:
– <script type="text/javascript">
document.write("<h1>Hello World!</h1>") ;
</script>
• Notes:
• The type attribute is to allow you to use other scripting languages
(but JavaScript is the default)
• This simple code does the same thing as just putting <h1>Hello
World!</h1> in the same place in the HTML document
• The semicolon at the end of the JavaScript statement is optional
• You need semicolons if you put two or more statements on the same
line
• It’s probably a good idea to keep using semicolons 7
Dealing with old browsers
• Some old browsers do not recognize script tags
• These browsers will ignore the script tags but will display the
included JavaScript
• To get old browsers to ignore the whole thing, use:
<script type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
• The <!-- introduces an HTML comment
• To get JavaScript to ignore the HTML close comment, -->, the //
starts a JavaScript comment, which extends to the end of the line
8
Where to put JavaScript
• JavaScript can be put in the <head> or in the <body> of
an HTML document
• JavaScript functions should be defined in the <head>???
• This ensures that the function is loaded before it is needed
• JavaScript in the <body> will be executed as the page loads
• JavaScript can be put in a separate .js file
– <script src="myJavaScriptFile.js"></script>
• Put this HTML wherever you would put the actual JavaScript code
• An external .js file lets you use the same JavaScript on multiple
HTML pages
• The external .js file cannot itself contain a <script> tag
9
• JavaScript can be put in HTML form object, such as a button
• This JavaScript will be executed when the form object is used
A Simple Script
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1-strict.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>A First Program in JavaScript</title>
<script type ="text/javascript">
<!--
document.writeln( //or window.alert after removing html tags
"<h1>Welcome to JavaScript Programming!</h1>");
//-->
</script>
</head>
10
<body></body>
</html>
The Script with Prompt box
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1-strict.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Using Prompt and Alert Boxes</title>
<script type ="text/javascript">
<!--
var name;
name = window.prompt("Please enter your name")
document.writeln("<h1>Hello, " + name +
", welcome to JavaScript
programming!</h1>");
//-->
</script>
</head>
<body>
11
<p>Click Refresh (or Reload) to run this script again</p>
</body>
</html>
Language Elements
• Variables
• Operators
• Control Statements
• Functions
• Objects

12
JavaScript Variables
• Untyped!(Implicit) :
foo = 6;

• Can be declared with var keyword (Explicit ):


var foo;

• Can be created automatically by assigning a value:


foo=1; blah="Hi Dave";

13
Variable Scope
• Global
• Declared outside functions
• Any variable implicitly defined

• Local
• Explicit declarations inside functions

• Note
• Variables can hold any valid type of value (Dynamic
Typing ), and can hold values of different types at 14
different times during execution.
Primitive data types
• JavaScript has three “primitive” types: number, string,
and boolean
• Everything else is an object
• Numbers are always stored as floating-point values
• Hexadecimal numbers begin with 0x
• Some platforms treat 0123 as octal, others treat it as decimal
• Strings may be enclosed in single quotes or double
quotes
• Strings can contains \n (newline), \" (double quote), etc.
• Booleans are either true or false
– 0, "0", empty strings, undefined, null, and NaN are false , other 15
values are true
Operators
• Arithmetic, comparison, assignment, bitwise, boolean (pretty
much just like C++).

+ - * / % ++ -- == != > <
&& || ! & | << >>

16
Arithmetic Operators
Operator Description Example Result

+ Addition x=2 4
y=2
x+y
- Subtraction x=5 3
y=2
x-y
* Multiplication x=5 20
y=4
x*y
/ Division 15/5 3
10/3 3.3333333333333335
% Modulus (division 5%2 1
remainder)
10%2 0
2%5 2
++ Increment x=5 x=6
17
x++
-- Decrement x=5 x=4
x--
Assignment Operators
Operator Example Is The Same As

= x=y x=y

+= x+=y x=x+y

-= x-=y x=x-y

*= x*=y x=x*y

/= x/=y x=x/y

%= x%=y x=x%y
18
Comparison Operators
Operator Description Example

== is equal to 5==8 returns false

=== is equal to (checks for both value x=5


and type)
y="5"

x==y returns true

x===y returns false

!= is not equal 5!=8 returns true

> is greater than 5>8 returns false

< is less than 5<8 returns true

>= is greater than or equal to 5>=8 returns false

<= is less than or equal to 5<=8 returns true


19
Logical Operators
Operator Description Example

&& and x=6

y=3

(x < 10 && y > 1) returns true

|| or x=6

y=3

(x==5 || y==5) returns false

! not x=6

y=3

20
!(x==y) returns true
Different from C++
• The + operator is used for addition (if both operands are
numbers)
-or-
• The + operator means string concatenation (if either one of the
operands is not a number)

21
Comments
• Comments are as in C or Java:
• Between // and the end of the line
• Between /* and */
• Java’s javadoc comments, /** ... */, are treated just the same
as /* ... */ comments; they have no special meaning in
JavaScript

22
Control Statements, I
• Most JavaScript statements are also borrowed from C
• Assignment: greeting = "Hello, " + name;
• Compound statement:
{ statement; ...; statement }
• If statements:
if (condition) statement;
if (condition) statement; else statement;
• Familiar loop statements:
while (condition) statement;
do statement while (condition);
for (initialization; condition; increment) statement;

23
Control Statements, II
• The switch statement:
switch (expression){
case label :
statement;
break;
case label :
statement;
break;
...
default : statement;
}
• Other familiar statements:
– break;
– continue;
• The empty statement, as in ;; or { } 24
Control Statements, III
• And few not in C
for (var in object)

with (object)

25
Javascript Functions
• The keyword function is used to define a function
(subroutine):

function add(x,y) {
return(x+y);
}
• No type is specified for arguments!

26
What is the value of:
add(3,4) 7

add(“3”,”4”) 34

add(“Hi”,”Dave”) “HiDave”

add(3,”Hi”) “3Hi”

add(“2.13blah”,3.14 “2.13blah3.14”
) 27
Javascript program
<SCRIPT>
function add(x,y) {
return(x+y);
}

document.write("add(3,4) is " + add(3,4) + "<BR>");


document.write("add(\"3\",\"4\") is " + add("3","4") +
"<BR>");
document.write("add(\"Hi\",\"Dave\") is " +
add("Hi","Dave") + "<BR>");
document.write("add(3,\"Hi\") is " + add(3,"Hi") +
"<BR>");
document.write("add(\"2.13blah\",3.14) is " +
add("2.13blah",3.14)); 28
</SCRIPT>
Recursion is supported
function factorial(x) {
// use <= 0 instead of < 0
// to avoid problems with neg numbers

if (x<=0)
return(1);
else
return( x * factorial(x-1));
}

document.write("<H3>11! = " +
factorial(11) + "</H3>"); 29
JavaScript Global Functions
Function Description
escape() Encodes a string that is not in ASCII character set
e.g. document.write(escape(“Hello! World.”))

eval() Evaluates a string and executes it as if it was script


code e.g. document.write("<br>" + eval("2+2"));

isFinite() Determines whether a value is a finite, legal number


Eg isFinite(123)-> true, isFinite("Hello")-> false

isNaN() Determines whether a value is an illegal number


Eg isNaN(123)-> false, isNaN("Hello")-> true

Number() Converts an object's value to a number


parseFloat() Parses a string and returns a floating point number

parseInt() Parses a string and returns an integer 30


String() Converts an object's value to a string
unescape() Decodes an encoded string
Objects in JavaScript
• Objects have attributes and methods.
• Many pre-defined objects and object types.
• Using objects follows the syntax of C++/Java:
objectname.attributename
objectname.methodname()
• JavaScript is not Object Oriented – but Object-
Based
31
Three ways to create an object
• You can use an object literal:
– var course = { number: "CIT597", teacher="Dr. Dave" }
• You can use new to create a “blank” object, and add fields
to it later:
– var course = new Object();
course.number = "CIT597";
course.teacher = "Dr. Dave";
• You can write and use a constructor:
– function Course(n, t) { // best placed in <head>
this.number = n;
this.teacher = t;
}
– var course = new Course("CIT597", "Dr. Dave"); 32
The document object
• Many attributes of the current document are available via the
document object:

Title Referrer
URL Images
Forms Links
Colors

33
document Methods
• document.write() like a print statement – the output
goes into the HTML document.
• document.writeln() adds a newline after printing.
• document.getElementById() Returns the element that
has the ID attribute with the specified value

document.write("My title is " +


document.title);

34
Example
<HEAD>
<TITLE>JavaScript is Javalicious</TITLE>
</HEAD>
<BODY>
<h3>I am a web page and here is my
name:</h3>
<script type=”text/Javascript”>
document.write(document.title);
</script>
<hr>
35
The navigator Object
• Represents the browser. Read-only!
• Attributes include:

appName
appVersion
platform

36
navigator Example

if (navigator.appName ==
"Microsoft Internet Explorer") {
document.writeln("<H1>This page
requires Netscape!</H1>");
}

37
The window Object
• Represents the current window.

• There are possible many objects of type Window, the


predefined object window represents the current window.
• Access to, and control of, a number of properties including
position and size.

38
window attributes
• document
• name
• status the status line
• parent

39
some window methods
alert()
close()
prompt()
moveTo() moveBy()
open()
scroll() scrollTo()
resizeBy() resizeTo()

40
The Math Object
• Access to mathematical functions and constants.
• Constants: Math.PI
• Methods:
Math.abs(), Math.sin(), Math.log(), Math.max(),
Math.pow(), Math.random(), Math.sqrt(), …

41
Math object in use
// returns an integer between 1 and 6
function roll() {
var x = Math.random();

// convert to range [0,6.0)


x = x * 6;
// add 1 and convert to int
return parseInt(1+x );
}

document.writeln("Roll is “ + roll() ); 42
Math object in use
<script type ="text/javascript">
<!--
var input1 = window.prompt("Enter first number", "0");
var input2 = window.prompt("Enter second number", "0");
var input3 = window.prompt("Enter third number", "0");
var value1 = parseFloat(input1);
var value2 = parseFloat(input2);
var value3 = parseFloat(input3);
var maxValue = maximum( value1, value2, value3);

document.writeln("First number: " + value1 +


"<br /> Second number: " + value2 +
"<br />Third number: " + value3 +
"<br />Maximum is: " +maxValue );

function maximum(x,y,z)
{
return Math.max(x,Math.max(y,z)); 43
}
//-->
</script>
Array Objects
• Arrays are supported as objects.

• Attribute length

• Methods include:
concat join pop push reverse sort

44
Some similarity to C++
• Array indexes start at 0.
• Syntax for accessing an element is the same:
a[3]++;
blah[i] = i*72;

45
New Stuff (different from
C++)
• Arrays can grow dynamically – just add new elements at the
end.
• Arrays can have holes, elements that have no value.
• Array elements can be anything
• numbers, strings, or arrays!

46
Four ways to create an array
• You can use an array literal:
var colors = ["red", "green", "blue"];
• You can use new Array() to create an empty array:
– var colors = new Array();
• You can add elements to the array later:
colors[0] = "red"; colors[2] = "blue"; colors[1]="green";
• You can use new Array(n) with a single numeric
argument to create an array of that size
– var colors = new Array(3);
• You can use new Array(…) with two or more arguments
to create an array containing those values:
47
– var colors = new Array("red","green", "blue");
The length of an array
• If myArray is an array, its length is given by
myArray.length
• Array length can be changed by assignment beyond the
current length
• Example: var myArray = new Array(5); myArray[10] = 3;
• Arrays are sparse, that is, space is only allocated for
elements that have been assigned a value
• Example: myArray[50000] = 3; is perfectly OK
• But indices must be between 0 and 232-1
• As in C and Java, there are no two-dimensional arrays; but
you can have an array of arrays: board[3][3]
48
Arrays examples
• car = { myCar: "Saturn", 7: "Mazda" }
– car[7] is the same as car.7
– car.myCar is the same as car["myCar"]
• If you know the name of a property, you can use dot notation:
car.myCar
• If you don’t know the name of a property, but you have it in a
variable (or can compute it), you must use array notation:
car["my" + "Car"]
• var colors = [" blue ",
" green ",
" yellow "];
var x = window.prompt("enter a number "); 49

document.body.style.background = colors[x];
Array of Arrays Example
var board = [ [1,2,3],
[4,5,6],
[7,8,9] ];

for (i=0;i<3;i++)
for (j=0;j<3;j++)
board[i][j]++;

50
Array functions
• If myArray is an array,
– myArray.sort() sorts the array alphabetically
– myArray.sort(function(a, b) { return a - b; }) sorts numerically
– myArray.reverse() reverses the array elements
– myArray.push(…) adds any number of new elements to the end of
the array, and increases the array’s length
– myArray.pop() removes and returns the last element of the array,
and decrements the array’s length
– myArray.toString() returns a string containing the values of the
array elements, separated by commas

51
Passing Arrays to Functions
• To pass an array argument to a function, specify the name of
the array without brackets.
var a = [1,2,3,4,5];

outputArray(" Your array: ", a);

function outputArray(heading, theArray)


{
document.writeln(heading + theArray.join("
") + " <br /> ");
} 52
Searching Array: Linear and
Binary Search…

53
The for…in statement
• You can loop through all the properties of an object with
for (variable in object) statement;
• Example: for (var prop in course) {
document.write(prop + ": " + course[prop]);
}
• Possible output: teacher: Dr. Dave
number: CIT597
• The properties are accessed in an undefined order
• If you add or delete properties of the object within the loop, it is
undefined whether the loop will visit those properties
• Arrays are objects; applied to an array, for…in will visit the
“properties” 0, 1, 2, …
54
• Note that course["teacher"] is equivalent to course.teacher
• You must use brackets if the property name is in a variable
The with statement
• with (object) statement ; uses the object as the default prefix
for variables in the statement
• For example, the following are equivalent:
– with (document.myForm) {
result.value = compute(myInput.value) ;
}
– document.myForm.result.value =
compute(document.myForm.myInput.value);

• One of the book hints at mysterious problems resulting from


the use of with, and recommends against ever using it

55
JavaScript Popup Boxes
• Alert Box
• An alert box is often used if you want to make sure
information comes through to the user.
• When an alert box pops up, the user will have to click
"OK" to proceed.
<script>
alert("Hello World!")
</script>

56
JavaScript Popup Boxes - 2
• Confirm Box
• A confirm box is often used if you want the user to verify or accept
something.
• When a confirm box pops up, the user will have to click either "OK"
or "Cancel" to proceed.
• If the user clicks "OK", the box returns true. If the user clicks
"Cancel", the box returns false.
<script>
function deleteRecord( id){
if(confirm("Are you sure you want to delete this record? ")){
window.location.href = ‘index.php?q=delete' + '&id=' + id;
} 57
}
</script>
JavaScript Popup Boxes - 3
• Prompt Box
• A prompt box is often used if you want the user to input a value
before entering a page.
• When a prompt box pops up, the user will have to click either
"OK" or "Cancel" to proceed after entering an input value.
• If the user clicks "OK“, the box returns the input value. If the user
clicks "Cancel“, the box returns null.

<script>
num1 = window.prompt("Enter the first number");
</script>
58
Exception handling, I
• Exception handling in JavaScript is almost the same as in
Java
• throw expression creates and throws an exception
• The expression is the value of the exception, and can be of any type
(often, it's a literal String)
• try {
statements to try
} catch (e) { // Notice: no type declaration for e
exception-handling statements
} finally { // optional, as usual
code that is always executed
}
• With this form, there is only one catch clause 59
Exception handling, II
• try {
statements to try
} catch (e if test1) {
exception-handling for the case that test1 is true
} catch (e if test2) {
exception-handling for when test1 is false and test2 is true
} catch (e) {
exception-handling for when both test1and test2 are false
} finally { // optional, as usual
code that is always executed
}
• Typically, the test would be something like
e == "InvalidNameException" 60
Warnings
• JavaScript is a big, complex language
• We’ve only scratched the surface
• It’s easy to get started in JavaScript, but if you need to use it
heavily, plan to invest time in learning it well
• Write and test your programs a little bit at a time
• JavaScript is not totally platform independent
• Expect different browsers to behave differently
• Write and test your programs a little bit at a time
• Browsers aren’t designed to report errors
• Don’t expect to get any helpful error messages
• Write and test your programs a little bit at a time

61
Exercise
1. (“The twelve Days of Christmas” Song) Write a script that
uses repetition and a switch structures to print the song “The
Twelve Days of Christmas.” You can find the words at the site
www.santas.net/twelvedaysofchristmas.htm
2. Write a script that prints the following diamond shape.
Note: all asterisks (*) should be printed by a single statement
Building an Online Quiz
• Online quizzes and polls are popular web applications often
used for educational purposes or just for fun, as a web
developer build a quiz using simple XHTML form and process
the results with Javascript. Your quiz must have three closed-
ended questions, you may use an array to represent several
possible answer choices in a single data structure.

63
The End

64