Javascript II
University of
Sunderland CITM05 Web Development Unit 1
Basic JavaScript
program
<html>
<head>
<title>JavaScript example</title>
</head>
<body>
<h1>JavaScript example</h1>
<script language=“JavaScript”>
<!-- hide JavaScript from old browsers
[Link](“<p>First JavaScript text!</p>”)
//-->
</script>
<p>Back to normal HTML text.</p>
</body>
</html>
University of
Sunderland CITM05 Web Development Unit 1
Comments in
JavaScript
• C/C++ style comments can be used:
// This is a single line comment
/* This is a multi-line
comment */
/*
Another multi-line comment
*/
University of
Sunderland CITM05 Web Development Unit 1
Data Types/Variables
• Variables are 'objects' which hold data.
• JavaScript is loosely-typed i.e. the data type is not
specified when the variable is declared
• Data types are automatically converted during execution.
• The following data types are allowed:
Numbers (integer & real) Valid values include: 45, -3, 89.175
Strings Valid values include: “Hello”
Boolean Valid values are true or false
Null a special keyword denoting a null
(zero) value
University of
Sunderland CITM05 Web Development Unit 1
Variable/Assignment
example
<script language = "JavaScript">
<!-- Hide JavaScript from old browsers
var num1 = 10
var num2 = 25
var name = “Giles"
result = num1 + num2
[Link]("<p>Hello ", name, "!</p>")
[Link]("<p>Result of calculation is ", result, "</p>")
//-->
</script>
University of
Sunderland CITM05 Web Development Unit 1
Assignment
operators
operator example description
= a =b a is assigned the value of b
+= a += b a =a +b
-= a -= b a =a - b
*= a *= b a =a * b
/= a /= b a =a / b
%= a %= b a =a % b
University of
Sunderland CITM05 Web Development Unit 1
Arithmetic Operators
operator example description
+ a +b addition
- a-b subtraction
* a*b multiplication
/ a/b division
% a %b modulus
++ a++ add 1 to a
++ ++a add 1 to a
-- a-- subtract 1 from a
-- --a subtract 1 from a
- -a a is negative a
University of
Sunderland CITM05 Web Development Unit 1
Decision Statements
• Decision statements are of the form:
if (condition)
{
true-statements
}
else
{
false-statements
}
• The else component is optional
University of
Sunderland CITM05 Web Development Unit 1
Logical &
Comparison
operators
operator example description
> a >b a greater than b
< a <b a less than b
>= a >= b a greater than or equal to b
<= a <= b a less than or equal to b
== a == b a equals b
!= a != b a not equal to b
&& a && b a is True and b is True
|| a|| b a is True or b is True
University of
Sunderland CITM05 Web Development Unit 1
Example of a while
loop
var a = 1
while (a <= 10)
{
[Link]("<p>a = ", a, "</p>")
a++
}
University of
Sunderland CITM05 Web Development Unit 1
While/Decision
Example
var a = 1
while (a <= 10)
{
[Link]("<p>a = ", a, "</p>")
if (a % 3 == 0)
{
[Link]("<p><em>a is divisible by 3</em><p>")
}
else
{
[Link]("<p>a is not divisible by 3<p>")
}
a++
}
University of
Sunderland CITM05 Web Development Unit 1
Fixed Repetition
• To repeat statements a fixed number of
times use a for loop:
for ([initial expression]; [conditional expression]; [update
expression])
{
statements
}
University of
Sunderland CITM05 Web Development Unit 1
Example of a for loop
var a
for (a = 1; a <= 10; a++)
{
[Link]("<p>a = ", a, "</p>")
}
University of
Sunderland CITM05 Web Development Unit 1
Demonstration:
[Link]
University of
Sunderland CITM05 Web Development Unit 1
Arrays
• An array is a collection of related data.
• Think of an array as a table.
• Array elements are accessed through their
subscripts.
• Note that array subscripts start at 0.
array: 45 11 78 34 12 55
subscripts: 0 1 2 3 4 5
An array subscript can also be called an index
University of
Sunderland CITM05 Web Development Unit 1
Arrays in JavaScript
• Arrays are defined/declared as:
var myArray = new Array()
var yearArray = new Array(12);
Data structures consisting of related data items (collections of
data items)
• JavaScript arrays are “dynamic” entities
– Can change size after being created
• Array elements are accessed via their subscript:
yearArray[3] = "March"
lastmonth = yearArray[12]
thismonth = yearArray[current]
University of
Sunderland CITM05 Web Development Unit 1
Array Example
var seasonArray = new Array(4)
var index
seasonArray[0] = "Spring"
seasonArray[1] = "Summer"
seasonArray[2] = "Autumn"
seasonArray[3] = "Winter"
for (index = 0; index < 4; index++)
{
[Link]("<p>", seasonArray[index], "</p>")
}
University of
Sunderland CITM05 Web Development Unit 1
Demonstration:
[Link]
University of
Sunderland CITM05 Web Development Unit 1
Functions
• Functions enable JavaScript code to be
broken down.
• This makes the code more readable.
• Functions can be called from multiple
locations.
• Functions should be defined in the <head>
section of the HTML file.
University of
Sunderland CITM05 Web Development Unit 1
JavaScript Functions
function name([parameters])
{
statements
[return expression]
}
• The return expression passes data back to
the calling statement.
• Multiple parameters are separated by
commas.
University of
Sunderland CITM05 Web Development Unit 1
Function Example
<head>
<title>JavaScript Example</title>
<script language = "JavaScript">
<!-- Hide JavaScript from old browsers
function sum(num1, num2)
{
var result
result = num1 + num2
return result
}
//-->
</script>
</head>
University of
Sunderland CITM05 Web Development Unit 1
Calling the sum
function
<body>
<h1>Sum Function</h1>
<script language = "JavaScript">
<!-- Hide JavaScript from old browsers
var firstNum = 10
var secondNum = 20
answer = sum(firstNum, secondNum)
[Link]("<p>The answer is ", answer, "</p>")
//-->
</script>
</body>
University of
Sunderland CITM05 Web Development Unit 1
Demonstration:
[Link]
University of
Sunderland CITM05 Web Development Unit 1
for / in
repetition structure
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"[Link]
<html xmlns = "[Link]
<head><title>for in</title>
<SCRIPT LANGUAGE = "JavaScript">
function forin()
{
var myArray = [ 12, 342, 63, 88, 995 ];
var sum = 0;
for ( var i in myArray )
sum += myArray[ i ];
[Link]( "<BR>Sum is: " + sum );
}
</SCRIPT>
</HEAD><BODY ONLOAD = "forin()"></BODY>
</body></html>
University of
Sunderland CITM05 Web Development Unit 1
Passing Arrays to
Functions
• To pass an array to a function
– Specify the name of the array without brackets
as a parameter
– You do not need to separately pass the size of
the array
• var myArray = [ 1, 2, 3, 4, 5 ];
• Somefunction( myArray );
University of
Sunderland CITM05 Web Development Unit 1
Sorting Arrays
• JavaScript has built in method sort for sorting
arrays
– By default uses string comparisons to determine sorting
order of Array elements
– Strings compared by ASCII values of their characters
– Takes as optional argument name of function
(comparator function) – compares two arguments and
returns following
• Negative value if first value < second value
• Zero if arguments are equal
• Positive value if first value > second value
• Functions can be considered data and be
assigned to variables and passed to functions
University of
Sunderland CITM05 Web Development Unit 1
Sorting Arrays
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"[Link]
<html xmlns = "[Link]
<head><title>Sorting</title>
<SCRIPT LANGUAGE = "JavaScript">
function sorting()
{
var myArray = [ 12, 342, 63, 88, 995 ];
[Link]( "<BR>Unsorted array is: " + myArray );
[Link]( myComparisonFunction );
[Link]( "<BR>Sorted array is: " + myArray );
} Not completely sorted!
function myComparisonFunction( value1, value2 ) Need more effective method
{ return parseInt( value1 ) > parseInt( value2 ); } e.g. Bubblesort and
</SCRIPT></HEAD><BODY ONLOAD = "sorting()"></BODY> MANY OTHER SORTS
</body></html>
University of
Sunderland CITM05 Web Development Unit 1
Other array features
• Searching Arrays:
– Linear Search and Binary Search
• Multiple-Subscripted Arrays
– var grades = [[ 77, 68, 86, 73 ],[ 23, 44, 55, 89 ]];
– grades[1][1] = 99;
University of
Sunderland CITM05 Web Development Unit 1