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

The JavaScript Language

CS 312: Internet programming and


• Learn about JavaScript
• Using JavaScript in HTML
• Language Elements
• Variables
• Operators
• Control Statements
• Functions
• Objects
• Exception handling.

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
• 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
• JavaScript is usually embedded directly into HTML pages
About JavaScript
• JavaScript was designed to add interactivity to HTML
• JavaScript is a scripting language (a scripting language is
a lightweight programming language)
• A JavaScript consists of lines of executable computer
• JavaScript is an interpreted language (means that scripts
execute without preliminary compilation)
• Everyone can use JavaScript without purchasing a license

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.

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

• When you are using sensitive or copyrighted data or

– Your JavaScript code is open to the public.

Using JavaScript in a browser
• JavaScript code is included within <script> tags:
– <script type="text/javascript">
document.write("<h1>Hello World!</h1>") ;
• 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
• 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!")
• 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
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
• 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"
<html xmlns = "http://www.w3.org/1999/xhtml">
<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>");
The Script with Prompt box
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<html xmlns = "http://www.w3.org/1999/xhtml">
<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
<p>Click Refresh (or Reload) to run this script again</p>
Language Elements
• Variables
• Operators
• Control Statements
• Functions
• Objects

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";

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
• 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
• Arithmetic, comparison, assignment, bitwise, boolean (pretty
much just like C++).

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

Arithmetic Operators
Operator Description Example Result

+ Addition x=2 4
- Subtraction x=5 3
* Multiplication x=5 20
/ Division 15/5 3
10/3 3.3333333333333335
% Modulus (division 5%2 1
10%2 0
2%5 2
++ Increment x=5 x=6
-- Decrement x=5 x=4
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
Comparison Operators
Operator Description Example

== is equal to 5==8 returns false

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

and type)

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

Logical Operators
Operator Description Example

&& and x=6


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

|| or x=6


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

! not x=6


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

• 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

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;

Control Statements, II
• The switch statement:
switch (expression){
case label :
case label :
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)

Javascript Functions
• The keyword function is used to define a function

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

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
function add(x,y) {

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

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

if (x<=0)
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:
• JavaScript is not Object Oriented – but Object-
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

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 " +


<TITLE>JavaScript is Javalicious</TITLE>
<h3>I am a web page and here is my
<script type=”text/Javascript”>
The navigator Object
• Represents the browser. Read-only!
• Attributes include:


navigator Example

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

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.

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

some window methods
moveTo() moveBy()
scroll() scrollTo()
resizeBy() resizeTo()

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(), …

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
Array Objects
• Arrays are supported as objects.

• Attribute length

• Methods include:
concat join pop push reverse sort

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

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

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:
– var colors = new Array("red","green", "blue");
The length of an array
• If myArray is an array, its length is given by
• 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]
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:
• 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],
[7,8,9] ];

for (i=0;i<3;i++)
for (j=0;j<3;j++)

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

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…

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, …
• 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 =

• One of the book hints at mysterious problems resulting from

the use of with, and recommends against ever using it

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.
alert("Hello World!")

JavaScript Popup Boxes - 2
• Confirm Box
• A confirm box is often used if you want the user to verify or accept
• 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.
function deleteRecord( id){
if(confirm("Are you sure you want to delete this record? ")){
window.location.href = ‘index.php?q=delete' + '&id=' + id;
} 57
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.

num1 = window.prompt("Enter the first number");
Exception handling, I
• Exception handling in JavaScript is almost the same as in
• 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
• 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

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
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.

The End