[go: up one dir, main page]

0% found this document useful (0 votes)
2 views25 pages

CITM05_week7_javascript3

The document provides an overview of basic JavaScript concepts, including functions, events, arrays, and the differences between passing by value and reference. It includes examples of how to define and call functions, use arrays, and manage their elements. Additionally, it explains how to pass arrays to functions and the implications of array equality in JavaScript.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views25 pages

CITM05_week7_javascript3

The document provides an overview of basic JavaScript concepts, including functions, events, arrays, and the differences between passing by value and reference. It includes examples of how to define and call functions, use arrays, and manage their elements. Additionally, it explains how to pass arrays to functions and the implications of array equality in JavaScript.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 25

Javascript III

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.

• Note: A function with no parameters must include the parentheses ()


after the function name
• Note: Do not forget about the importance of capitals in JavaScript! The
word function must be written in lowercase letters, otherwise a
JavaScript error occurs! Also note that you must call a function with the
exact same capitals as in the function name.

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>

<script type="text/javascript"> document.write(myFunction())


</script>

<p>The script in the body section calls a function.</p>


<p>The function returns a text.</p>
</body>
</html>
University of
Sunderland CITM05 Web Development Unit 1
Arguments and return value
<html>
<head>
<script type="text/javascript">
function product(a,b)
{
return a*b
}
</script>
</head>

<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

• 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
• Arrays are one way of keeping a program more organized.
• They allow you to do some things that are difficult without
them.
• Arrays are usually a group of the same variable type that
use an index number to distinguish them from each other.
• Suppose you wanted to write out 5 quotes, and use
variables for each one of the quotes.
• You could define 5 variables:
quote1="I like JavaScript.";
quote2="I used to like Java.";
quote3="JavaScript rules.";
quote4="Help! JavaScript Error!";
quote5="Just Kidding.";

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

// b[1] still equals 2 again


function a(b)
{ return b+2; }

var b = new Array [1,2,3];


c = a(b[1]);
University of
Sunderland CITM05 Web Development Unit 1
Pass by reference

// b[1] will equal four after this


// code has run
function a(b)
{ return b[1]+2; }

var b = new Array [1,2,3];


c = a(b[1]);

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) { }

// This if statement will equate to false


var a = new Array(1, 2, 3);
var b = new Array(1, 2, 3);
if (a == b) { }
University of
Sunderland CITM05 Web Development Unit 1
Adding Elements to an
Array
• With JavaScript, the length of an array is just its current length.
• The following is a perfectly valid set of statements.

var aName = new Array(10);


aName[20] = 'top';

• 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

You might also like