ENG1003 Lecture Notes - Lecture 4: Return Statement, Eval, Anonymous Function

78 views6 pages
Week 4: Functions
Why use?
No duplication of code for a task to be performed multiple
times at different locations in code
1.
Provides single pt of guaranteed consistent update
2.
If parameterised, each call can be made with diff parameter
values to get slightly diff behav
3.
Code hierarchies -calling sub-code to perform sub-tasks -
incr. productivity + reduce error rates by narrowing focus
4.
Isolates internal data and code operating on data frm outside
world
5.
*need to have well-defined input (AKA parameters) and output data
pipelines (AKA return values)
SYNTAX.
var
aVariable = 7;
myFunction(argument1, argument 2); //Function call
function
myFunction(parameter1, parameter2)
//Function declaration
{ //Body of function
var
now =
new
Date();
var
output = "";
var
sum = number1 + number2;
output = sum.toFixed(2) + " (calculated at: " +
now.toLocaleTimeString() + ")"; //return of
function
alert(output);
}
Function name: addAndTimeStamp
Parameters: number1, number2
Body of function: {}
Code within function only executed when function called
by code outside
!
Arguments can be any exprssn VS parameter must have
variable name. BOTH matched by having same position in
respective argument and parameter lists of functn call
and decl.
!
To make output be displayed normally and not as pop-up,
change function so it returns output String rather than
displaying the result itself.
!
Variables
Function declaration
Anonymous functn: (var [name] = function(){};
To use in callbacks and for handling events
!
Scope management -can be used to create temporary/private
scope
!
Handy in closures and recursions (functns that call
themselves)
!
**
Scope
Any code that accesses a particular variable, either to set
or get value
!
Variables declared w/ "var" keyword outside any functn,
scope is ALL code associated w/ webpg --> global variables
!
Variables declared w/ "var" keyword inside any functn,
scope is ENTIRE function, cannot be accessed outside
functn --> local variables
Eg. Parameters = local var initialised in special way
More advisable bcos limits unwanted interference w/
code outside functn
!
In a browser, global scope ident with global object
window
!
Lifetime
Global: frm when declared until webpg closed
!
Local: created when functn called -including parameters,
don't exist when functn terminates, "reborn" each separate
time function is called
!
JS moves all var declarations within functions to the top,
no matter where in functn they are declared
!
Scoping/nested functn
Can only be called frm within parent functn -helps to
simplify things and ensure no confusion with all other code
on webpg
!
Constructor functn
Mechanism to create objects w/ ident sets of properties w/o
error
!
Called with new operator, creating new object
!
May also assign initial values bcos of parameter values
!
Name begins with upper case letter (remind us to use with
new)
!
First class functn
Considered first-class if can be passed to other functions
as arguments
!
Can be assigned to a var, and can be passed as a parameter
to a functn (just like a var)
!
Var referencing a functn can be used to invoke functn
!
When passing a functn as a parameter, can pass a ref to the
functn, or just define functn anonymly in place of
parameter (eg. flexible)
If too diff to read syntax, assign anonym functns to
var b4 the call, then use vars as argums
!
Declare var that references functn above
var function1 = addAndTimeStamp;
1.
RHS anonym functn declaratn
var function2 = function(number1, number2)
{
var now = new Date();
var sum = number1 * number2;
var result = sum.toFixed(2) + "
(calculated at: " + now.toLocaleTimeString()
+ ")";
return result;
}
2.
Call myFunction
output += addAndTimeStamp(1, 2) + "<br />";
3.
Call functn referenced by function1 var
output += function1(3, 4) + "<br />";
4.
Call functn referenced by function2 var
output += function2(5, 6) + "<br />";
5.
Callback functn
Basically API functn
!
Expected to code w/ parameter list specified in API
documentatn
!
In turn, API functn will call ur functn whenever
appropriate, possibly supply useful parameter values each
time functn is called
!
Someone else calls functn to let you know of a certain
event's occurrence -eg when Google Maps finishes loading
its map
!
Eg. "&callback=initMap"
!
if
(navigator.geolocation)
{
var
positionOptions = {
enableHighAccuracy:
true
,
timeout: Infinity,
maximumAge: 0
};
//following HOOKS UP THE showCurrentLocation CALLBACK
function (see below)
navigator.geolocation.watchPosition(showCurrentLocati
on, errorHandler, positionOptions);
}
// CALLBACK function: fires whenever a new reading is
detected
function
showCurrentLocation(position)
{
// Demonstrate the current latitude and longitude:
document.getElementById("latValue").innerHTML =
Number(position.coords.latitude).toFixed(4);
document.getElementById("longValue").innerHTML =
Number(position.coords.longitude).toFixed(4);
document.getElementById("accuracyValue").innerHTML =
Number(position.coords.accuracy).toFixed(2);
position: object passed to us by geolocation API whenever
functn is called
!
*(function() {
//all JS code for the file
})()
Function call -any executable code within will execute as it is
loaded
*in Immediately Invoked Functn Expression, vars and functns
declared within will not join global scope, but share scope of
anonymous functn
*helps to include JS files in webpg w/o var and func name
collisions
"#$%&'()(*&#+,
-./0.1234
5/67839:4;<;.=:7.2;>.2734;:?.:;
./3;60>39;:@;.;A79=:0@9;B?39;
=.22096;0:
C./.83:3/4;<;>./0.123;:?.:;
3D04:4;@92E;B?023;A79=:9;04;13096;
=.223FG;60>39;>.2734;=.223F;
./67839:4
H79=:0@94
:3D:;<;:3D:I:@)@B3/J.43KLM
N=?.9634;7OO3/=.43;:@;2@B3/=.43;A@/;O.209F/@834
PP59@9E8@74;A79=:0@9;@92E;8.Q34;43943;
0A;0:;B@9R:;13;=.223F; A/@8;.9EB?3/3;3243;
:?/@76?@7:;=@F3;N743;9.83F;A79=:94;A@/;
:?.:I
%74:;O7:;1/.=Q3:4 .A:3/;A79=:9; 9.83G; @/;
B@9R:; B@/QI;
S@9R:;A@/63:;T74:;13=.743; 9@;O./.83:3/4I
var
outputAreaRef =
document.getElementById("outputArea");
var
aVariable = 7;
alert(addAndTimeStamp(1, 2)); //in popup
outputAreaRef.innerHTML = "Sum = " +
addAndTimeStamp(Math.sin(0.5), aVariable + 10);
function
addAndTimeStamp(number1, number2)
{
var
now =
new
Date();
var
sum = number1 + number2;
var
result = sum.toFixed(2) + " (calculated at: " +
now.toLocaleTimeString() + ")";
return
result; //displ. in div on webpg
}
Function can execute while calling statement only partially
executed, since call occurs as it is encountered during eval
of expr it is embedded in
!
Return statement specifying value to return and terminating
execution of funct
!
When func returns to calling code, call replaced by return
value in the expr call was embedded in, then calling
statement continues eval until completn
!
Week$4:$Functions
"734F.EG; UV;%./=?;WXUY
UZ,XZ
Unlock document

This preview shows pages 1-2 of the document.
Unlock all 6 pages and 3 million more documents.

Already have an account? Log in
Week 4: Functions
Why use?
No duplication of code for a task to be performed multiple
times at different locations in code
1.
Provides single pt of guaranteed consistent update2.
If parameterised, each call can be made with diff parameter
values to get slightly diff behav
3.
Code hierarchies -calling sub-code to perform sub-tasks -
incr. productivity + reduce error rates by narrowing focus
4.
Isolates internal data and code operating on data frm outside
world
5.
*need to have well-defined input (AKA parameters) and output data
pipelines (AKA return values)
SYNTAX.
var
aVariable = 7;
addAndTimeStamp(1, 2);
myFunction(argument1, argument 2); //Function call
function
myFunction(parameter1, parameter2)
//Function declaration
{ //Body of function
var
now =
new
Date();
var
output = "";
var
sum = number1 + number2;
output = sum.toFixed(2) + " (calculated at: " +
now.toLocaleTimeString() + ")"; //return of
function
alert(output);
}
Function name: addAndTimeStamp
Parameters: number1, number2
Body of function: {}
Code within function only executed when function called
by code outside
!
Arguments can be any exprssn VS parameter must have
variable name. BOTH matched by having same position in
respective argument and parameter lists of functn call
and decl.
!
To make output be displayed normally and not as pop-up,
change function so it returns output String rather than
displaying the result itself.
!
Variables
Function declaration
Anonymous functn: (var [name] = function(){};
To use in callbacks and for handling events
!
Scope management -can be used to create temporary/private
scope
!
Handy in closures and recursions (functns that call
themselves)
!
**
Scope
Any code that accesses a particular variable, either to set
or get value
!
Variables declared w/ "var" keyword outside any functn,
scope is ALL code associated w/ webpg --> global variables
!
Variables declared w/ "var" keyword inside any functn,
scope is ENTIRE function, cannot be accessed outside
functn --> local variables
Eg. Parameters = local var initialised in special way
More advisable bcos limits unwanted interference w/
code outside functn
!
In a browser, global scope ident with global object
window
!
Lifetime
Global: frm when declared until webpg closed
!
Local: created when functn called -including parameters,
don't exist when functn terminates, "reborn" each separate
time function is called
!
JS moves all var declarations within functions to the top,
no matter where in functn they are declared
!
Scoping/nested functn
Can only be called frm within parent functn -helps to
simplify things and ensure no confusion with all other code
on webpg
!
Constructor functn
Mechanism to create objects w/ ident sets of properties w/o
error
!
Called with new operator, creating new object
!
May also assign initial values bcos of parameter values
!
Name begins with upper case letter (remind us to use with
new)
!
First class functn
Considered first-class if can be passed to other functions
as arguments
!
Can be assigned to a var, and can be passed as a parameter
to a functn (just like a var)
!
Var referencing a functn can be used to invoke functn
!
When passing a functn as a parameter, can pass a ref to the
functn, or just define functn anonymly in place of
parameter (eg. flexible)
If too diff to read syntax, assign anonym functns to
var b4 the call, then use vars as argums
!
Declare var that references functn above
var function1 = addAndTimeStamp;
1.
RHS anonym functn declaratn
var function2 = function(number1, number2)
{
var now = new Date();
var sum = number1 * number2;
var result = sum.toFixed(2) + "
(calculated at: " + now.toLocaleTimeString()
+ ")";
return result;
}
2.
Call myFunction
output += addAndTimeStamp(1, 2) + "<br />";
3.
Call functn referenced by function1 var
output += function1(3, 4) + "<br />";
4.
Call functn referenced by function2 var
output += function2(5, 6) + "<br />";
5.
Callback functn
Basically API functn
!
Expected to code w/ parameter list specified in API
documentatn
!
In turn, API functn will call ur functn whenever
appropriate, possibly supply useful parameter values each
time functn is called
!
Someone else calls functn to let you know of a certain
event's occurrence -eg when Google Maps finishes loading
its map
!
Eg. "&callback=initMap"
!
if
(navigator.geolocation)
{
var
positionOptions = {
enableHighAccuracy:
true
,
timeout: Infinity,
maximumAge: 0
};
//following HOOKS UP THE showCurrentLocation CALLBACK
function (see below)
navigator.geolocation.watchPosition(showCurrentLocati
on, errorHandler, positionOptions);
}
// CALLBACK function: fires whenever a new reading is
detected
function
showCurrentLocation(position)
{
// Demonstrate the current latitude and longitude:
document.getElementById("latValue").innerHTML =
Number(position.coords.latitude).toFixed(4);
document.getElementById("longValue").innerHTML =
Number(position.coords.longitude).toFixed(4);
document.getElementById("accuracyValue").innerHTML =
Number(position.coords.accuracy).toFixed(2);
position: object passed to us by geolocation API whenever
functn is called
!
*(function() {
//all JS code for the file
})()
Function call -any executable code within will execute as it is
loaded
*in Immediately Invoked Functn Expression, vars and functns
declared within will not join global scope, but share scope of
anonymous functn
*helps to include JS files in webpg w/o var and func name
collisions
"#$%&'()(*&#+,
-./0.1234
5/67839:4;<;.=:7.2;>.2734;:?.:;
./3;60>39;:@;.;A79=:0@9;B?39;
=.22096;0:
C./.83:3/4;<;>./0.123;:?.:;
3D04:4;@92E;B?023;A79=:9;04;13096;
=.223FG;60>39;>.2734;=.223F;
./67839:4
H79=:0@94
:3D:;<;:3D:I:@)@B3/J.43KLM
N=?.9634;7OO3/=.43;:@;2@B3/=.43;A@/;O.209F/@834
PP59@9E8@74;A79=:0@9;@92E;8.Q34;43943;
0A;0:;B@9R:;13;=.223F; A/@8;.9EB?3/3;3243;
:?/@76?@7:;=@F3;N743;9.83F;A79=:94;A@/;
:?.:I
%74:;O7:;1/.=Q3:4 .A:3/;A79=:9; 9.83G; @/;
B@9R:; B@/QI;
S@9R:;A@/63:;T74:;13=.743; 9@;O./.83:3/4I
var
outputAreaRef =
document.getElementById("outputArea");
var
aVariable = 7;
alert(addAndTimeStamp(1, 2)); //in popup
outputAreaRef.innerHTML = "Sum = " +
addAndTimeStamp(Math.sin(0.5), aVariable + 10);
function
addAndTimeStamp(number1, number2)
{
var
now =
new
Date();
var
sum = number1 + number2;
var
result = sum.toFixed(2) + " (calculated at: " +
now.toLocaleTimeString() + ")";
return
result; //displ. in div on webpg
}
Function can execute while calling statement only partially
executed, since call occurs as it is encountered during eval
of expr it is embedded in
!
Return statement specifying value to return and terminating
execution of funct
!
When func returns to calling code, call replaced by return
value in the expr call was embedded in, then calling
statement continues eval until completn
!
Week$4:$Functions
"734F.EG; UV;%./=?;WXUY UZ,XZ
Unlock document

This preview shows pages 1-2 of the document.
Unlock all 6 pages and 3 million more documents.

Already have an account? Log in

Document Summary

Must put brackets after functn name, or won"t work. **anonymous function only makes sense if it won"t be called from anywhere else throughout code - use named functns for that. Arguments = actual values that are given to a function when calling it. Parameters = variable that exists only while functn is being called, given values called arguments. No duplication of code for a task to be performed multiple times at different locations in code. If parameterised, each call can be made with diff parameter values to get slightly diff behav. Code hierarchies - calling sub-code to perform sub-tasks - incr. productivity + reduce error rates by narrowing focus. Isolates internal data and code operating on data frm outside world. *need to have well-defined input (aka parameters) and output data pipelines (aka return values) Syntax. var avariable = 7; addandtimestamp(1, 2); myfunction(argument1, argument 2); //function call function myfunction(parameter1, parameter2)

Get access

Grade+20% off
$8 USD/m$10 USD/m
Billed $96 USD annually
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
40 Verified Answers
Class+
$8 USD/m
Billed $96 USD annually
Class+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
30 Verified Answers

Related Documents