SY306 Set5 JavaScriptFunctions
SY306 Set5 JavaScriptFunctions
http://www.w3schools.com/js/default.asp
Function Definitions
• Syntax and terminology:
function function-name( parameter-list )
{
declarations and statements
}
• Example
/* Returns the sum of x and y */
function doAdd(x, y) {
var sum = x + y;
return sum;
}
1
Function Invocation
• Built-in functions
• User-defined functions
g = 7;
h = 5;
Output?
2
JavaScript Scope Rules
• Global Scope
– Declared explicitly (with var) outside a function
– Declared implicitly (without var) inside a function
• Function Scope
– Declared explicitly (with var) inside a function
– Parameters
3
Exercise #2 – What’s the output?
function fun1 (x) {
x = x + 3;
y = y + 4;
document.writeln("<br> FUN1: "+x+ "," +y);
}
function fun2 () {
var y;
x = x + 10;
y = y + 20;
document.writeln("<br> FUN2: "+x+ "," +y);
}
x = 1;
y = 2;
4
Connecting JavaScript and HTML
– In a separate file
<script type = “text/javascript” src = “calc.js” >
</script>
• Length of array
arr.length;
• Cell assignment
arr[3] = 190;
arr[3] = “hello”;
5
…but were afraid to ask
function initializeArrays()
{
var n1 = new Array( 5 ); // allocate 5-element Array
var n2 = new Array(); // allocate empty Array
initializeArrays();
Example output
6
Scope – Revisited
function mystery( x, y )
{
for ( var ii = 0; ii < x.length; ++ii )
x[ii] = x[ii] * y;
y = 7;
document.writeln("<br/> x: ",x);
document.writeln("<br/> y: ",y);
}
• .push
• .indexOf
• .sort
• .sort(comparatorFunction)
7
Exercise #4
a.) Write a function “sumArray” as follows:
Input: an array
Output: the sum of that array
b.) Write test code to create an array and call “sumArray” on it.
printme (array1);
printme (array2[1]);
printme (x);
array1[x] = 57;
printme (array1);
8
JavaScript Secrets
JavaScript Tips
• Quoting
document.writeln("<a href=\"cat.html\">cat</a>");
vs.
document.writeln("<a href='cat.html'>cat</a>");
document.writeln("<h1>",heading,"</h1>");