COMP519 Web Programming
Lecture 13: JavaScript (Part 4)
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
1 Functions
Defining a Function
Calling a function
Variable-length Argument Lists
Static Variables
2 Scope
Definitions
Variable Declarations Revisited
Functions and Scope
COMP519 Web Programming Lecture 13 Slide L13 1
Functions Defining a Function
Functions
Function definitions can take several different forms in JavaScript
including:
function identi f i e r ( param1 , param2 , ...) {
statem e n t s }
identi f i e r = function ( param1 , param2 , ...) {
statem e n t s }
Such function definitions are best placed in the head section
of an HTML page or in a library that is then imported
Function names are case-sensitive
The function name must be followed by parentheses
A function has zero, one, or more parameters that are variables
Parameters are not typed
identifier.length can be used inside the body of the function to
determine the number of parameters
COMP519 Web Programming Lecture 13 Slide L13 2
Functions Defining a Function
Functions
Function definitions can take several different forms in JavaScript
including:
function identi f i e r ( param1 , param2 , ...) {
statem e n t s }
identi f i e r = function ( param1 , param2 , ...) {
statem e n t s }
The return statement
return value
can be used to terminate the execution of a function and to make
value the return value of the function
The return value does not have to be of a primitive type
A function can contain more than one return statement
Different return statements can return values of different types
; there is no return type for a function
COMP519 Web Programming Lecture 13 Slide L13 3
Functions Calling a function
Calling a Function
A function is called by using the function name followed by a list of
arguments in parentheses
function identi f i e r ( param1 , param2 , ...) {
...
}
... identifi e r ( 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
function sum ( num1 , num2 ) { return num1 + num2 }
sum1 = sum (5 ,4) // sum1 = 9
sum2 = sum (5 ,4 ,3) // sum2 = 9
sum3 = sum (5) // sum3 = NaN
COMP519 Web Programming Lecture 13 Slide L13 4
Functions Calling a function
‘Default Values’ for Parameters
ECMAScript 2015 introduced default parameter values
function sum ( num1 = 0 , num2 = 0) { return num1 + num2 }
sum1 = sum (5 ,4) // sum1 = 9
sum2 = sum (5 ,4 ,3) // sum2 = 9
sum3 = sum (5) // sum3 = 5
In Internet Explorer or other older browsers, a function instead has to
check whether an argument has the value undefined and take
appropriate action
function sum ( num1 , num2 ) {
if ( num1 == un d e f ined ) num1 = 0
if ( num2 == un d e f ined ) num2 = 0
return num1 + num2
}
COMP519 Web Programming Lecture 13 Slide L13 5
Functions Calling a function
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
COMP519 Web Programming Lecture 13 Slide L13 6
Functions Variable-length Argument Lists
Variable-length Argument Lists
Every JavaScript function has a property called arguments
The arguments property consists of an array of all the arguments
passed to a function
As for any JavaScript array, arguments.length can be used to
determine the number of arguments
// Function that returns the sum of all its argu m e n t s
function sumA ll () {
var sum = 0
for ( var i =0; i < arguments . length ; i ++)
sum = sum + a r g u ments [ i ]
return sum
}
sum0 = sumAll () // sum0 = 0
sum1 = sumAll (5) // sum1 = 5
sum2 = sumAll (5 ,4) // sum2 = 9
sum3 = sumAll (5 ,4 ,3) // sum3 = 12
COMP519 Web Programming Lecture 13 Slide L13 7
Functions Static Variables
JavaScript Functions and Static Variables
JavaScript does not have a static keyword to declare a variable to be
static and preserve its value between different calls of a function
A solution is to use a function property instead
function counter () {
counter . count = counter . count || 0 // function property
counter . count ++
return counter . count
}
document . writel n ("1: static count = "+ counter ())
document . writel n ("2: static count = "+ counter ())
document . writel n ("3: global counter . c ount = "+ counter . count )
1: st atic count = 1
2: st atic count = 2
3: gl obal counter . count = 2
As the example shows the function property is global/public
Private static variables require more coding effort
COMP519 Web Programming Lecture 13 Slide L13 8
Scope Definitions
Scope
Name Binding
An association of a name to an entity
Example: The association of a variable name to a ‘container’ for values
Scope of a Name Binding
The region of a program where the binding is valid, that is, where the
name can be used to a refer to the entity
Typical regions are
entire program (global)
block
function
expression
execution context
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
Variable Declarations Revisited
Variables can be declared (within a scope) using one of the following
statements:
var va riabl e1 , vari able2 , ...
var variable1 = value1 , var i a b l e 2 = value2 , ...
The second statement also initialises the variables
Used inside a function definition, creates a local variable, only accessible
within the function
Used outside a function definition, creates a global variable
A variable can be defined without an explicit declaration
by assigning a value to it:
variable = value
Always creates a global variable
COMP519 Web Programming Lecture 13 Slide L13 11
Scope Variable Declarations Revisited
Variable Declarations Revisited
Variables can be declared (within a block context) using one of the
following statements:
let va riabl e1 , vari able2 , ...
let variable1 = value1 , var i a b l e 2 = value2 , ...
The second statement also initialises the variables
Used inside a block, creates a local variable, only accessible within the block
Used outside any block, creates a global variable
for ( var i =0; i <1; i ++) {
var j = i + 1
console . log (I: i = ,i , j =,j)
}
console . log (O: i = ,i , j =,j)
I: i = 0 j = 1
O: i = 1 j = 1
for ( let i =0; i <1; i ++) {
let j = i + 1
console . log (I: i = ,i , j =,j)
}
console . log (O: i = ,i , j =,j)
I: i = 0 j = 1
Ref e rence E rror : i is not d efined
Ref e rence E rror : j is not d efined
COMP519 Web Programming Lecture 13 Slide L13 12
Scope Variable Declarations Revisited
Variable Declarations Revisited
Variables can be declared (within a block context) using one of the
following statements:
let va riabl e1 , vari able2 , ...
let variable1 = value1 , var i a b l e 2 = value2 , ...
Variable declarations using let are not hoisted
var my Var 1
console . log (" my Var 1 =" , m yVa r1 )
console . log (" my Var 2 =" , m yVa r2 )
var my Var 2
my Var 1 = u ndef ined
my Var 2 = u ndef ined
let my Var 1
console . log (" my Var 1 =" , m yVa r1 )
console . log (" my Var 2 =" , m yVa r2 )
let my Var 2
my Var 1 = u ndef ined
Ref e rence E rror : myV ar2 is not d efined
COMP519 Web Programming Lecture 13 Slide L13 13
Scope Functions and Scope
Functions and Scope (1)
x = " Hello "
function f1 () {
console . log ("1: " + x)
}
function f2 () {
console . log ("2: " + x)
x = " Bye "
console . log ("3: " + x)
}
f1 ()
f2 ()
console . log ("4: " + x)
1: Hello
2: Hello
3: Bye
4: Bye
A variable defined or declared
outside any function is global
A global variable can be accessed
from any part of the script,
including inside a function
COMP519 Web Programming Lecture 13 Slide L13 14
Scope Functions and Scope
Functions and Scope (2)
x = " Hello "
function f1 () {
console . log ("1: " + x)
}
function f2 () {
console . log ("2: " + x)
var x = " Bye "
console . log ("3: " + x)
}
f1 ()
f2 ()
console . log ("4: " + x)
1: Hello
2: undefined
3: Bye
4: Hello
A variable defined or declared
outside any function is global
A global variable can be accessed
from any part of the script,
including inside a function
To create a local variable inside a
function we need to declare it
(and optionally initialise it)
A global and a local variable can
have the same name but are still
different name bindings
COMP519 Web Programming Lecture 13 Slide L13 15
Scope Functions and Scope
Functions and Scope (3)
x = " Hello "
function f1 () {
console . log ("1: " + x)
}
function f2 () {
// Name binding of x ?
console . log ("2: " + x)
let x = " Bye "
console . log ("3: " + x)
}
f1 ()
f2 ()
console . log ("4: " + x)
1: Hello
console . log ("2: " + x)
^
Refer e nceErro r : x is not
defined
A variable defined or declared
outside any function is global
A global variable can be accessed
from any part of the script,
including inside a function
To create a local variable inside a
function we need to declare it
(and optionally initialise it)
A global and a local variable can
have the same name but are still
different name bindings
COMP519 Web Programming Lecture 13 Slide L13 16
Scope Functions and Scope
Functions and Scope (4)
x = " Hello "
function f3 ( x) {
x += !
console . log ("1: " + x)
}
f3 ( Bye )
console . log ("2: " + x)
f3 (x )
console . log ("2: " + x)
1: Bye !
2: Hello
1: Hello !
2: Hello
Parameters are local variables
unrelated to any global variables
of the same name
COMP519 Web Programming Lecture 13 Slide L13 17
Scope Functions and Scope
Static vs Dynamic Scoping
let s = static
function f1 () {
console . log ( scope = , s )
}
function f2 () {
let s = dynamic
f1 ()
}
f2 ()
// Trace :
// let s = static
// f2 ()
// let s = dynamic
// f1 ()
// console . log ( scope = , s )
scope = static
JavaScript uses static scoping
The example also works with
var instead of let
COMP519 Web Programming Lecture 13 Slide L13 18
Scope Functions and Scope
Nested Function Definitions
function f1 () {
var x = 1
f2 ()
function f2 () {
var y = 2
console . log ( x = ,x, y = ,y)
}
}
f1 ()
f2 ()
x = 1 y = 2
scope2 . js :11
f2 ()
^
Refer e nceErro r : f2 is not defined
Function definitions can be
placed anywhere where a
statement is allowed
; but browser semantics
may differ
Function definitions can be
nested
; works across browsers
Inner functions are local to
outer functions
Function definitions are
hoisted: A function call can
appear in the code before
the function definition
(but this is bad style)
COMP519 Web Programming Lecture 13 Slide L13 19
Scope Functions and Scope
Scope and Recursive Functions
function factorial ( x) {
console . log ( 1: y =, y)
var y = x
console . log ( 2: y =, y)
if (y > 1) {
y = x * f a c t orial (x -1)
}
console . log ( 3: y =, y)
return y
}
factorial (2)
// factorial (2)
1: y = un d e f i ned
2: y = 2
// factorial (1)
1: y = un d e f i ned
2: y = 1
3: y = 1
// y = 2 * 1
3: y = 2
A function can call itself from within its code (recursion)
Every function call creates a new scope
COMP519 Web Programming Lecture 13 Slide L13 20
Scope Functions and Scope
Revision and Further Reading
Read
Chapter 20: The JavaScript Language: User-Defined Functions
of S. Schafer: Web Standards Programmer’s Reference.
Wiley Publishing, 2005.
Harold Cohen Library 518.532.S29 or
E-book http://library.liv.ac.uk/record=b2174141
Read
Chapter 5: Reference Types: The Function Type
of N. C. Zakas: Professional JavaScript for Web developers.
Wrox Press, 2009.
Harold Cohen Library 518.59.Z21 or
E-book http://library.liv.ac.uk/record=b2238913
Data & Object Factory: JS Function Objects
https://www.dofactory.com/tutorial/javascript-function-objects
COMP519 Web Programming Lecture 13 Slide L13 21