JavaScript (Part 4)- Functions and Scope
JavaScript (Part 4)- Functions and Scope
Ullrich Hustadt
1 Functions
Defining a Function
Calling a function
Variable-length Argument Lists
Static Variables
2 Scope
Definitions
Variable Declarations Revisited
Functions and Scope
Functions
Function definitions can take several different forms in JavaScript
including:
function identifier ( param1 , param2 , ...) {
statements }
Functions
Function definitions can take several different forms in JavaScript
including:
function identifier ( param1 , param2 , ...) {
statements }
Calling a Function
A function is called by using the function name followed by a list of
arguments in parentheses
function identifier ( param1 , param2 , ...) {
...
}
... identifier ( arg1 , arg2 ,...) ... // Function call
• The list of arguments can be shorter as well as longer as
the list of parameters
• If it is shorter, then any parameter without corresponding argument
will have value undefined
Functions as Arguments
JavaScript functions are objects and can be passed as arguments to other
functions
function apply (f ,x , y ) {
return f (x , y )
}
function mult (x , y ) {
return x * y
}
console . log ( ’2 * 3 = ’ , apply ( mult ,2 ,3))
2 * 3 = 6
console . log ( ’2 + 3 = ’ ,
apply ( function (a , b ) { return a + b } ,
2 ,3))
2 + 3 = 5
Scope
Name Binding
An association of a name to an entity
Name Resolution
Resolution of a name to the entity it is associated with
COMP519 Web Programming Lecture 13 Slide L13 – 9
Scope Definitions
Scope
Static Scope/Scoping
Name resolution depends on the location in the source code and the
lexical context, which is defined by where a named variable or function is
defined/declared
Dynamic Scope/Scoping
Name resolution depends on the program state when a name is
encountered which is determined by the execution context or calling
context
Global / Local
• A name binding is global if its scope is the entire program and local
otherwise
• A variable is global if the name binding of its name is global and local
otherwise
COMP519 Web Programming Lecture 13 Slide L13 – 10
Scope Variable Declarations Revisited
for ( var i =0; i <1; i ++) { for ( let i =0; i <1; i ++) {
var j = i + 1 let j = i + 1
console . log ( ’ I : i = ’ ,i , ’ j = ’ , j ) console . log ( ’ I : i = ’ ,i , ’ j = ’ , j )
} }
console . log ( ’ O : i = ’ ,i , ’ j = ’ , j ) console . log ( ’ O : i = ’ ,i , ’ j = ’ , j )
I: i = 0 j = 1 I: i = 0 j = 1
O: i = 1 j = 1 ReferenceError : i is not defined
ReferenceError : j is not defined
function f2 () {
let s = ’ dynamic ’
f1 ()
}
f2 ()
// Trace :
// let s = ’ static ’
// f2 ()
// let s = ’ dynamic ’
// f1 ()
// console . log ( ’ scope = ’ , s )
scope = static
COMP519 Web Programming Lecture 13 Slide L13 – 18
Scope Functions and Scope