COMP284 Scripting Languages
Lecture 11: JavaScript (Part 2)
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
1 Control structures
Blocks
Conditional statements
Switch statements
While- and Do While-loops
For-loops
Try, throw, catch, finally statements
Variable Declarations Revisited
2 Arrays
Definition
forEach-method
Array functions
COMP284 Scripting Languages Lecture 11 Slide L11 1
Control structures
Control structures
JavaScript control structures
block statements
conditional statements
switch statements
while- and do while-loops
for-loops
try, throw, catch finally statements
are syntactically identical to those of Java
COMP284 Scripting Languages Lecture 11 Slide L11 2
Control structures Blocks
Control structures: block statements
A block statement is a sequence of zero or more statements delimited
by a pair of curly brackets
{
statements
}
It allows to use multiple statements where JavaScript expects only one
statement
{
var x = 1
var y = x ++
}
COMP284 Scripting Languages Lecture 11 Slide L11 3
Control structures Conditional statements
Control structures: conditional statements
Conditional statements take the following form in JavaScript:
if ( condition )
statement
else if ( condition )
statement
else
statement
There are no elsif- or elseif-clauses in JavaScript
The else-clause is optional but there can be at most one
Each statement can be a block statement
JavaScript also supports conditional expressions
condition ? if_true _ e x p r : if_false_ e x p r
COMP284 Scripting Languages Lecture 11 Slide L11 4
Control structures Switch statements
Control structures: switch statement
Switch statements in JavaScript take the same form as in PHP:
switch ( expr ) {
case expr1 :
statements
break ;
case expr2 :
statements
break ;
defaul t :
statements
break ;
}
there can be arbitrarily many case-clauses
the default-clause is optional but there can be
at most one
expr is evaluated only once and then compared
to expr1, expr2, etc using (loose) equality ==
once two expressions are found to be equal the
corresponing clause is executed
if none of expr1, expr2, etc are equal to expr,
then the default-clause will be executed
break ‘breaks out’ of the switch statement
if a clause does not contain a break command,
then execution moves to the next clause
COMP284 Scripting Languages Lecture 11 Slide L11 5
Control structures Switch statements
Control structures: switch statement
Not every case-clause needs to have associated statements
Example:
switch ( month ) {
case 1: case 3: case 5: case 7:
case 8: case 10: case 12:
days = 31;
break ;
case 4: case 6: case 9: case 11:
days = 30;
break ;
case 2:
days = 28;
break ;
defaul t :
days = 0;
break ;
}
COMP284 Scripting Languages Lecture 11 Slide L11 6
Control structures While- and Do While-loops
Control structures: while- and do while-loops
JavaScript offers while-loops and do while-loops
while ( condition )
statement
do
statement
while ( condition )
Example:
// Compute the factorial of a given n umber
var factorial = 1;
do {
factorial *= number --
} while ( number > 0)
COMP284 Scripting Languages Lecture 11 Slide L11 7
Control structures For-loops
Control structures: for-loops
for-loops in JavaScript take the form
for ( initia l i sa t io n ; test ; i n crement )
statement
var factorial = 1
for ( var i = 1; i <= number ; i ++)
factorial *= i
A for-loop is equivalent to the following while-loop:
initial i s a ti on
while ( test ) {
statement
increment
}
for ( var f a c t o r i a l = 1; number ; number - -)
factorial *= number
COMP284 Scripting Languages Lecture 11 Slide L11 8
Control structures For-loops
Control structures: for-loops
In JavaScript, initialisation and increment can consist of more
than one statement, separated by commas instead of semicolons
for (i = 1, j = 1; j >= 0; i++ , j --)
document . wr i teln ( i + " * " + j + " = " + i*j )
// Indenta t i o n has no ` meanin g ' in JavaScript ,
// the next line is not part of the loop !! BAD STYLE !!
document . wr i teln ( " Outside loop : i = " + i + "j = " + j)
1 * 1 = 1
2 * 0 = 0
Outsid e loop : i = 3 | j = -1
Note: Variables declared with var inside a for-loop are still visible
outside
for ( var i = 0; i < 1; i ++)
document . wr i teln ( " Inside loop : i = " + i)
document . wr i teln ( " Outside loop : i = " + i)
Inside loop : i = 0
Outsid e loop : i = 1
COMP284 Scripting Languages Lecture 11 Slide L11 9
Control structures For-loops
Control structures: break and continue
The break command can also be used in while-, do while-, and for-loops
and discontinues the execution of the loop
while ( value < 100) {
if ( value == 0) break ;
value ++
}
The continue command stops the execution of the current iteration of a
loop and moves the execution to the next iteration
for (x = -2; x <= 2; x ++) {
if (x == 0) continue ;
document . wr i teln ( " 10 / " + x + " = " + (10/ x ));
}
10 / -2 = -5
10 / -1 = -10
10 / 1 = 10
10 / 2 = 5
COMP284 Scripting Languages Lecture 11 Slide L11 10
Control structures Try, throw, catch, finally statements
Error handling
When a JavaScript statement generates an error, an exception is thrown
Exceptions can also explicitly be thrown via a throw statement
A try ... catch ... statement allows for error / exception handling
try { statements }
catch ( error ) { stat e m e n t s }
finall y { statements }
Statements in the try block are executed first
If any statement within the try block throws an exception, control
immediately shifts to the catch block
error is a variable used to store the error / exception
Statements in the finally block are executed after try and catch
statements, regardless of whether an exception was thrown or caught
Curly brackets are necessary even where a block consists of only one
statement
COMP284 Scripting Languages Lecture 11 Slide L11 11
Control structures Try, throw, catch, finally statements
Error handling
When a JavaScript statement generates an error, an exception is thrown
Exceptions can also explicitly be thrown via a throw statement
A try ... catch ... statement allows for error / exception handling
throw e x p r e s s i on
A throw statement throws (generates) an exception and interrupts the
normal flow of control
The exception expression can be a string, a number, a boolean or an
object
try ... catch ... statements can be nested
COMP284 Scripting Languages Lecture 11 Slide L11 12
Control structures Try, throw, catch, finally statements
Error handling: Example
x = "A"
try {
if ( isNaN (x )) throw " x is NaN "
y = x. toFixed (2)
} catch (e ) {
document . wr i teln ( ' Caught : ' + e)
y = 0
} finally {
document . wr i teln ( 'y = ' ,y)
}
Caught TypeError : x. toFixed is not a function
y = 0
COMP284 Scripting Languages Lecture 11 Slide L11 13
Control structures Variable Declarations Revisited
Variable Declarations Revisited
Variables can be declared (within a scope) using one of the following
statements:
var variable1 , variable2 , ...
var variable1 = value1 , v a r i a ble2 = 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
COMP284 Scripting Languages Lecture 11 Slide L11 14
Control structures Variable Declarations Revisited
Variable Declarations Revisited
Variables can be declared (within a block context) using one of the
following statements:
let variable1 , variable2 , ...
let variable1 = value1 , v a r i a ble2 = 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 renc eErro r : i is not defined
Ref e renc eErro r : j is not defined
COMP284 Scripting Languages Lecture 11 Slide L11 15
Control structures Variable Declarations Revisited
Variable Declarations Revisited
Variables can be declared (within a block context) using one of the
following statements:
let variable1 , variable2 , ...
let variable1 = value1 , v a r i a ble2 = value2 , ...
Variable declarations using let are not hoisted
var myVar1
console .log ( " myVa r1 = " ,myVar1 )
console .log ( " myVa r2 = " ,myVar2 )
var myVar2
my Var 1 = unde fin ed
my Var 2 = unde fin ed
let myVar1
console .log ( " myVa r1 = " ,myVar1 )
console .log ( " myVa r2 = " ,myVar2 )
let myVar2
my Var 1 = unde fined
Ref e renc eErro r : myVar2 is not defined
COMP284 Scripting Languages Lecture 11 Slide L11 16
Arrays Definition
Arrays
An array is created by assigning an array value to a variable
var arrayVar = []
var arrayVar = [ elem0 , elem1 , ... ]
JavaScript uses
arrayVar [ index ]
to denote the element stored at position index in arrayVar
The first array element has index 0
Arrays have no fixed length and it is always possible to add more
elements to an array
Accessing an element of an array that has not been assigned a value yet
returns undefined
For an array arrayVar, arrayVar.length returns the maximal index
index such that arrayVar[index] has been assigned a value
(including the value undefined) plus one
COMP284 Scripting Languages Lecture 11 Slide L11 17
Arrays Definition
Arrays
It is possible to assign a value to arrayVar.length
if the assigned value is greater than the previous value of arrayVar.length,
then the array is ‘extended’ by additional undefined elements
if the assigned value is smaller than the previous value of arrayVar.length,
then array elements with greater or equal index will be deleted
Assigning an array to a new variable creates a reference to the
original array
; changes to the new variable affect the original array
Arrays are also passed to functions by reference
The slice function can be used to create a proper copy of an array:
object arrayVar.slice(start, end)
returns a copy of those elements of array variable that have indices
between start and end
COMP284 Scripting Languages Lecture 11 Slide L11 18
Arrays Definition
Arrays: Example
var array1 = ['hello', [1, 2], function() {return 5}, 43]
document.writeln("1: array1.length = "+array1.length)
1: array1.length = 4
document.writeln("2: array1[3] ="+array1[3])
2: array1[3] = 43
array1[5] = 'world'
document.writeln("3: array1.length = "+array1.length)
3: array1.length = 6
document.writeln("4: array1[4] ="+array1[4])
4: array1[4] = undefined
document.writeln("5: array1[5] ="+array1[5])
5: array1[5] = world
array1.length = 4
document.writeln("6: array1[5] ="+array1[5])
6: array1[5] = undefined
var array2 = array1
array2[3] = 7
document.writeln("7: array1[3] ="+array1[3])
7: array1[3] = 7
COMP284 Scripting Languages Lecture 11 Slide L11 19
Arrays forEach-method
forEach-method
The recommended way to iterate over all elements of an array is a
for-loop
for ( index = 0; index < arrayVar . length ; index ++) {
... arrayVar [ index ] ...
}
An alternative is the use of the forEach method:
var callback = function ( elem , index , arrayArg ) {
statements
}
arrayVar . fo r Each ( callback );
The forEach method takes a function as an argument
It iterates over all indices/elements of an array
It passes the current array element (elem), the current index (index) and
a pointer to the array (arrayArg) to the function
Return values of that function are ignored,
but the function may have side effecs
COMP284 Scripting Languages Lecture 11 Slide L11 20
Arrays forEach-method
forEach-method: Example
var myArray = [' Michele Zito ' ,' Ullrich Hustadt ' ];
var rewr i t e N am e s = function ( elem , index , arr ) {
arr [ index ] = elem . repl a ce (/(\ w +)\ s (\ w +)/ , "$2 , $1 " );
}
myArra y . forEach ( rewriteN a m e s );
for (i =0; i < myAr ray . length ; i ++) {
document . write (' [ '+ i+ ' ] = '+ my Array [i ]+ " ");
}
[0] = Zito , Miche le [1] = Hustadt , Ullr ich
COMP284 Scripting Languages Lecture 11 Slide L11 21
Arrays Array functions
Array operators
JavaScript has no stack or queue data structures,
but has stack and queue functions for arrays:
number array.push(value1, value2,...)
appends one or more elements at the end of an array;
returns the number of elements in the resulting array
mixed array.pop()
extracts the last element from an array and returns it
mixed array.shift()
shift extracts the first element of an array and returns it
number array.unshift(value1, value2,...)
inserts one or more elements at the start of an array variable;
returns the number of elements in the resulting array
Note: In contrast to PHP, array does not need to be a variable
COMP284 Scripting Languages Lecture 11 Slide L11 22
Arrays Array functions
Array operators: push, pop, shift, unshift
planets = ["earth"]
planets.unshift("mercury","venus")
planets.push("mars","jupiter","saturn");
document.writeln("planets\@1: "+planets.join(" "))
planets@1: mercury venus earth mars jupiter saturn
last = planets.pop()
document.writeln("planets\@2: "+planets.join(" "))
planets@2: mercury venus earth mars jupiter
first = planets.shift()
document.writeln("planets\@3: "+planets.join(" "))
planets@3: venus earth mars jupiter
document.writeln(" \@4: "+first+" "+last)
@4: mercury saturn
home = ["mercury","venus","earth"].pop()
document.writeln(" \@5: " + home)
@5: earth
number = ["earth"].push("mars");
document.writeln(" \@6: " + number)
@6: 2
COMP284 Scripting Languages Lecture 11 Slide L11 23
Revision
Revision
Read
Chapter 14: Expressions and Control Flow in JavaScript
Chapter 15: JavaScript Functions, Objects, and Arrays
of
R. Nixon: Learning PHP, MySQL & JavaScript:
with jQuery, CSS & HTML5. O’Reilly, 2018.
COMP284 Scripting Languages Lecture 11 Slide L11 24