CITM05_week7_javascript3
CITM05_week7_javascript3
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
document.write(“<p>First JavaScript text!</p>”)
//-->
</script>
<p>Back to normal HTML text.</p>
</body>
</html>
University of
Sunderland CITM05 Web Development Unit 1
JavaScript Functions
• To keep the browser from executing a script as
soon as the page is loaded, you can write your
script as a function.
• A function contains some code that will be
executed only by an event or by a call to that
function.
• You may call a function from anywhere within the
page (or even from other pages if the function is
embedded in an external .js file).
• Functions are defined at the beginning of a page, in
the <head> section.
University of
Sunderland CITM05 Web Development Unit 1
Example
<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!")
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!"
onclick="displaymessage()" >
</form>
</body>
</html>
University of
Sunderland CITM05 Web Development Unit 1
Events
• If the line:
– alert("Hello world!!"),
• in the example before had not been written within a
function, it would have been executed as soon as
the line was loaded.
• Now, the script is not executed before the user hits
the button.
• We have added an onClick event to the button that
will execute the function displaymessage() when
the button is clicked.
University of
Sunderland CITM05 Web Development Unit 1
How to Define a Function
• The syntax for creating a function is:
function functionname(var1,var2,...,varX)
{ some code }
• var1, var2, etc are variables or values passed into the function.
• The { and the } defines the start and end of the function.
University of
Sunderland CITM05 Web Development Unit 1
The return Statement
• The return statement is used to specify the value that is
returned from the function.
• So, functions that are going to return a value must use the
return statement.
• Example
• The function below should return the product of two
numbers (a and b):
function prod(a,b) { x=a*b return x }
• When you call the function above, you must pass along two
parameters:
product=prod(2,3)
• The returned value from the prod() function is 6, and it will
be stored in the variable called product.
University of
Sunderland CITM05 Web Development Unit 1
How to call a function.
<html>
<head>
<script type="text/javascript">
function myfunction()
{
alert("HELLO")
}
</script>
</head>
<body>
<form>
<input type="button"
onclick="myfunction()"
value="Call function">
</form>
<p>By pressing the button,
a function will be called.
The function will alert a message.</p>
</body>
</html>
University of
Sunderland CITM05 Web Development Unit 1
Function with arguments
<html>
<head>
<script type="text/javascript">
function myfunction(txt)
{
alert(txt)
}
</script>
</head>
<body>
<form>
<input type="button"
onclick="myfunction('Hello')"
value="Call function">
</form>
<p>By pressing the button,
a function with an argument will be called.
The function will alert
this argument.</p>
</body>
</html>
University of
Sunderland CITM05 Web Development Unit 1
Function with arguments
<html>
<head>
<script type="text/javascript">
function myfunction(txt)
{
alert(txt)
}
</script>
</head>
<body>
<form>
<input type="button" onclick="myfunction('Good Morning!')"
value="In the Morning">
<input type="button" onclick="myfunction('Good Evening!')"
value="In the Evening">
</form>
<p>
When you click on one of the buttons, a function will be called.
The function will alert
the argument that is passed to it.
</p>
</body>
</html>
University of
Sunderland CITM05 Web Development Unit 1
Function that returns a
value
<html>
<head>
<script type="text/javascript">
function myFunction()
{
return ("Hello, have a nice day!")
}
</script>
</head>
<body>
<body>
<script type="text/javascript">
document.write(product(4,3))
</script>
<p>The script in the body section calls a function
with two parameters (4 and 3).</p>
<p>The function will return the product
of these two parameters.</p>
</body>
</html>
University of
Sunderland CITM05 Web Development Unit 1
Arrays
array: 45 11 78 34 12 55
subscripts: 0 1 2 3 4 5
University of
Sunderland CITM05 Web Development Unit 1
Arrays
• However, a better way may be to use an array. To
define an array, we need to follow the following
form:
var Name_of_Array= new Array(number_of_elements);
• Name_of_Array would be the name you want to
give the array variable, the number_of_elements
is the number of variables you want the array to
store. So, for our quotes, we could write:
var quote= new Array(5);
University of
Sunderland CITM05 Web Development Unit 1
Arrays
• Now, to assign values, we are going to use what is
called an index number, and place it inside
brackets. We attach this right on the end of the
word quote, so our first quote would be:
quote[0]
• Zero instead of 1.
• Arrays just work that way, the first element is
always zero and the last element is always one less
than what you define as the number of elements.
University of
Sunderland CITM05 Web Development Unit 1
Arrays
• In this case, our first element is quote[0], the
last is quote[4].
• So to assign the values we had, we could use a
straight assignment, like this:
var quote= new Array(5)
quote[0]="I like JavaScript.";
quote[1]="I used to like Java.";
quote[2]="JavaScript rules.";
quote[3]="Help! JavaScript Error!";
quote[4]="Just Kidding.";
University of
Sunderland CITM05 Web Development Unit 1
Arrays and Loops
• Notice that when we do this, we leave off the semicolon at the end of the
array definition, and use semicolons at the end of each element we
define.
• So far, it has only made things more complicated.
• However, this array can now be used as part of a loop, using the value
of the index numbers as a variable:
var x=0;
for (x=0; x<5; x++)
{
alert(quote[x]);
}
• This uses the variable x in place of each index number, and runs the
alert for all 5 elements in our array.
• The first time through, you would get an alert with quote[0], the
second time, quote[1], and so on.
University of
Sunderland CITM05 Web Development Unit 1
Example
• The script in action is a bit
<HEAD> annoying.
<SCRIPT language="JavaScript">
<!-- • You can write this script in
function display_quote() the head section.
{
var quote= new Array(5) • We will make this into a
quote[0]="I like JavaScript."; function, and call it from a link
quote[1]="I used to like Java."; (the link must be in the body)
quote[2]="JavaScript rules.";
quote[3]="Help! JavaScript Error!";
quote[4]="Just Kidding.";
var x=0;
for (x=0; x<5; x++)
{
alert(quote[x]);
}
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<A HREF="javascript:display_quote()">Click Here, I dare you!</A>
</BODY>
University of
Sunderland CITM05 Web Development Unit 1
Pass by Value /
Pass by Reference
• When passing a single value as an argument to a functions you must refer to the
element being passed, not the array itself.
• If you just use the array name, then what you are passing is the array, not its
values.
• It is also important to understand the difference between pass by value and pass
by reference with arrays.
• Primitive data types are passed by value.
• This means that when you pass them to a function or use them in an assignment
statement, what gets passed is the value, not the variable itself.
• A copy of the value is made to be passed to the function or variable.
• Arrays and objects, on the other hand, are passed by reference.
• This means that when you pass them to a function or use them in an assignment
statement, the reference to the variable is passed.
• No new copy is created.
• Instead, the function argument or variable is pointed to, or set to reference, the
same location in memory.
• Thus, any changes you make affect the original.
• Array elements are passed based on the value of its contents, it is the array itself
that is automatically passed by reference.
University of
Sunderland CITM05 Web Development Unit 1
Pass by value
// b will still equal two after this code has run
function a(b)
{ return b+2; }
var b = 2;
c = a(b);
University of
Sunderland CITM05 Web Development Unit 1
Equal arrays.
• Also two different arrays are not equal unless they reference the same
location in memory.
• If you want to compare the values of array elements, then you have to
compare the values of individual array elements.
// This if statement will equate to true
var a = new Array(1, 2, 3);
var b = a;
if (a == b) { }
• After these two statements run, the array will contain twenty-one elements, all of them
undefined except for the twenty-first element (aName[20]).
• Don't forget we started with zero.
• In other words, you can add elements to the end of the array with no problem.
• JavaScript makes use of what are called sparse arrays, which means that no matter how
many elements there are in the array, it only makes space in memory for those that have
been specificially declared.
• The above array would only have stored information on eleven elements, aName[0]
through aName[9] and aName[20].
• On the other hand, if you do a for .. in statement, it will still walk through every element that
could potentially have a value.
• In other words, from zero to the highest position declared, in sequence, without skipping
any, even if they are empty.
• This is not a problem for twenty-one elements, but potentially a big problem if the first
value is in position aName[1000000].
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