COMP519 Web Programming
Lecture 14: JavaScript (Part 5)
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Arrays Arrays Literals
Array Literals
An array literal is a comma-separated list of values enclosed in
square brackets
[2 ,3 ,5 ,7 ,11]
Each element of that list has an index position
given by the number of other elements preceding it
; the first index position is 0
[2 ,3 ,5 ,7 ,11]
| | | | |
0 1 2 3 4
The values in an array literal do not need to be of the same type
[2 , two ,3," three " ,1.1 e1 , true ]
The values in an array literal can include other array literals
(nested array literal)
[2 ,[3 ,5] ,[7 ,[11]]]
COMP519 Web Programming Lecture 14 Slide L14 1
Arrays Arrays Literals
Operators on Array Literals
It is possible to access an element of an array literal via its index
position: arrayLiteral[index]
[2 ,3 ,5 ,7 ,11][1] // retu rns 3
For a nested array literal, it is possible to iterate this access operation
[2 ,[3 ,5] ,[7 ,[11]]][1] // retu rns [3 ,5]
| | |
0 1 2
[2 ,[3 ,5] ,[7 ,[11]]][1][0] // retu rns 3
The length operation returns the number of elements in an array
literal: arrayLiteral.length
[2 ,3 ,5 ,7 ,11]. leng th // retu rns 5
We will discuss more operators in the context of array variables
COMP519 Web Programming Lecture 14 Slide L14 2
Arrays Definition
Arrays
An array is created by assigning an array literal to a variable
var a r r ayVar = []
var a r r ayVar = [elem0 , elem1 , ... ]
All operations that can be performed on array literals can be performed
on arrays:
arrayVar[index] returns the element at position index
arrayVar.length returns the length of the array
(highest index position plus one)
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
COMP519 Web Programming Lecture 14 Slide L14 3
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
COMP519 Web Programming Lecture 14 Slide L14 4
Arrays Definition
Arrays: Example
var array1 = [ hello , [1 , 2] , f uncti on () { return 5} , 43]
con sole . log ("1: array1 . length = "+ array1 . length )
con sole . log ("2: array1 [3] ="+ a rray 1 [3])
1: ar ray1 . len gth = 4
2: ar ray1 [3] = 43
array1 [5] = world
con sole . log ("3: array1 . length = "+ array1 . length )
con sole . log ("4: array1 [4] ="+ a rray 1 [4])
con sole . log ("5: array1 [5] ="+ a rray 1 [5])
3: ar ray1 . len gth = 6
4: ar ray1 [4] = un define d
5: ar ray1 [5] = world
array1 . le ngth = 4
con sole . log ("6: array1 [5] ="+ a rray 1 [5])
6: ar ray1 [5] = un define d
var array2 = a rray 1
array2 [3] = 7
con sole . log ("7: array1 [3] ="+ a rray 1 [3])
7: ar ray1 [3] = 7
COMP519 Web Programming Lecture 14 Slide L14 5
Arrays Iteration: for-loop and forEach-method
forEach-method
The recommended way to iterate over all elements of an array is a
for-loop
for ( ind ex = 0; ind ex < ar r a y Var . le ngth ; index ++) {
... a r r ayVar [ i ndex ] ...
}
An alternative is the use of the forEach method:
var c a l lback = f unction (elem , index , arra y A rg ) {
statemen t s
}
arr ay . forEach ( cal l b ack );
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
COMP519 Web Programming Lecture 14 Slide L14 6
Arrays Iteration: for-loop and forEach-method
forEach-method
var rewriteNames = f unction (elem , index , arr ) {
arr [ index ] = elem . replace (/(\ w +)\s (\ w +)/ , "$2 , $1 ");
}
var m yArray = [ Dave Jackson , Ullrich Hustadt ];
myAr ray . forE ach ( rewriteNames );
for (i =0; i < myA rray . le ngth ; i ++) {
cons ole . log ( myAr ray [ +i + ] = + myArra y [i ]);
}
myAr ray [0] = Jackson , Dave
myAr ray [1] = Hustadt , Ullrich
COMP519 Web Programming Lecture 14 Slide L14 7
Arrays Example
Arrays and Functions: Example
funct ion b ubble_sort ( array ) {
if (!( array && array . construct o r == Array ))
throw (" Argum e nt not an array ")
for ( let i =0; i < array . length ; i ++) {
for ( let j =0; j < array . length -i; j ++) {
if ( array [ j +1] < array [ j ]) {
// swap can change array becau se array is
// p assed by r eference
swap ( array , j , j +1)
}
}
}
return array
}
funct ion swap ( array , i , j ) {
let tmp = array [i]
array [ i ] = array [j]
array [ j ] = tmp
}
COMP519 Web Programming Lecture 14 Slide L14 8
Arrays Example
Arrays and Functions: Example
Inner functions have access to the variables of outer functions
funct ion b ubble_sort ( array ) {
funct ion swap (i , j) {
// swap can change array becau se array is
// a local v a riable of the outer function bubbl e _ s ort
let tmp = array [i ];
array [ i ] = array [j ];
array [ j ] = tmp ;
}
if (!( array && array . construct o r == Array ))
throw (" Argum e nt not an array ")
for ( var i =0; i < array . length ; i ++) {
for ( var j =0; j < array . length -i; j ++) {
if ( array [ j +1] < array [ j ]) swap (j, j +1)
} }
return array }
COMP519 Web Programming Lecture 14 Slide L14 9
Arrays Example
Arrays and Functions: Example
funct ion b ubble_sort ( array ) { ... }
array = [20 ,4 ,3 ,9 ,6 ,8 ,5 ,10]
cons ole . log (" array before sorti ng " +
array . join (" , "))
sorted = bubble _ s o rt ( array . slice (0)) // slice c reates copy
cons ole . log (" array after so rting of copy " +
array . join (" , "))
sorted = bubble _ s o rt ( array )
cons ole . log (" array after so rting of itself " +
array . join (" , "))
cons ole . log (" sorted array " +
sorted . join (" , "))
array be fore sorting 20 , 4, 3 , 9, 6 , 8 , 5 , 10
array after sortin g of copy 20 , 4, 3, 9, 6, 8 , 5 , 10
array after sortin g of itse lf 3, 4, 5 , 6 , 8 , 9, 10, 20
sorted array 3, 4, 5, 6, 8 , 9 , 10 , 20
COMP519 Web Programming Lecture 14 Slide L14 10
Arrays Array functions
Stacks and Queues
Stack
A collection of items that are inserted and removed according to the
last-in first-out (LIFO) principle
push adds an item to the top of the stack
pop removes the top item from the stack
Queue
A collection of items that are inserted and removed according to the
first-in first-out (FIFO) principle
enqueue adds an item to the back of the queue
dequeue removes the item at the front of the queue
COMP519 Web Programming Lecture 14 Slide L14 11
Arrays Array functions
Array functions
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 (enqueue);
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 (dequeue) 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
COMP519 Web Programming Lecture 14 Slide L14 12
Arrays Array functions
Array operators: push, pop, shift, unshift
plan ets = [" earth "]
plan ets . unsh ift (" mercu ry " ," venus ")
plan ets . push (" mars " ," jupiter " ," sat urn ");
cons ole . log (" planets []: " + plane ts . join (" "))
plan ets []: mercu ry venus earth mars jupiter saturn
last = p lanets . pop ()
cons ole . log (" last : " + pla nets . join (" "))
cons ole . log (" planets []: " + plane ts . join (" "))
last : saturn
plan ets []: mercu ry venus earth mars jupiter
first = planets . shift ()
cons ole . log (" first : " + first )
cons ole . log (" planets []: " + plane ts . join (" "))
first : m ercury
plan ets []: venus earth mars jupiter
number = [" earth "]. push (" mars ");
cons ole . log (" number : " + numbe r )
number : 2
COMP519 Web Programming Lecture 14 Slide L14 13
Equality and Program Behaviour
Equality and Program Behaviour
Why do we care whether 5 == true is true or false?
; it influences how our programs behave
; it influences whether more complex objects are equal or not
JavaScript:
if (5) document . writeln ("5 is true ");
else docum ent . writeln ("5 is not true ")
docum ent . writeln (" and ")
if (5 == true ) doc u ment . wri teln ("5 is equal to true ")
else docum ent . writeln ("5 is not equal to true ")
Output: 5 is true and 5 is not equal to true
PHP:
if (5) print ("5 is true ");
else print ("5 is not true ");
print (" and ");
if (5 == true ) print ("5 is equal to true ");
else print ("5 is not equal to true ");
Output: 5 is true and 5 is equal to true
COMP519 Web Programming Lecture 14 Slide L14 14
Equality and Program Behaviour
Equality and Program Behaviour
Why do we care whether 5 == true is true or false?
; it influences how our scripts behave
; it influences whether more complex objects are equal or not
JavaScript:
$arr ay3 = ["1.23 e2 " ,5]
$arr ay4 = ["12.3 e1 " , true ]
if (( $ array3 [1] == $ array4 [1]) && ( $ar ray3 [2] == $array4 [2]))
cons ole . log (" The two array s are equal ")
else c onsole . log (" The two a rrays are not equal ")
Output: The two arrays are not equal
PHP:
$arr ay3 = array ("1 .23 e2 " ,5);
$arr ay4 = array ("1 2.3 e1 ", true );
if (( $ array3 [1] == $ array4 [1]) && ( $ar ray3 [2] == $array4 [2]))
print (" The two arrays are equal ");
else print (" The two array s are not equal ");
Output: The two arrays are equal
COMP519 Web Programming Lecture 14 Slide L14 15
Equality and Program Behaviour
Equality and Program Behaviour
Note: The way in which more complex data structures are compared
also differs between PHP and JavaScript
JavaScript:
$arr ay3 = ["1.23 e2 " ,5]
$arr ay4 = ["12.3 e1 " , true ]
if ( $arra y3 == $arra y4 )
cons ole . log (" The two array s are equal ")
else c onsole . log (" The two a rrays are not equal ")
Output: The two arrays are not equal
PHP:
$arr ay3 = array ("1 .23 e2 " ,5);
$arr ay4 = array ("1 2.3 e1 ", true );
if ( $arra y3 == $arra y4 )
print (" The two arrays are equal ");
else print (" The two array s are not equal ");
Output: The two arrays are equal
COMP519 Web Programming Lecture 14 Slide L14 16
Equality and Program Behaviour
Equality and Program Behaviour
Note: The way in which more complex data structures are compared
also differs between PHP and JavaScript
JavaScript:
$arr ay3 = ["1.23 e2 " ,5]
$arr ay4 = ["1.23 e2 " ,5]
if ( $arra y3 == $arra y4 )
cons ole . log (" The two array s are equal ")
else c onsole . log (" The two a rrays are not equal ")
Output: The two arrays are not equal
PHP:
$arr ay3 = array ("1 .23 e2 " ,5);
$arr ay4 = array ("1 2.3 e1 " ,5);
if ( $arra y3 == $arra y4 )
print (" The two arrays are equal ");
else print (" The two array s are not equal ");
Output: The two arrays are equal
COMP519 Web Programming Lecture 14 Slide L14 17
JavaScript Libraries
JavaScript libraries
Collections of JavaScript functions (and other code), libraries,
can be stored in one or more files and then be reused
By convention, files containing a JavaScript library are given
the file name extension .js
<script>-tags are not allowed to occur in the file
A JavaScript library is imported using
< s cript src =" url " > </ script >
where url is the (relative or absolute) URL for library
< s cript src =" http :// cgi . csc . liv . ac . uk/
ullr ich / jsLib . js " >
</ script >
One such import statement is required for each library
Import statements are typically placed in the head section of a page or
at the end of the body section (see next slide)
Web browers typically cache libraries
COMP519 Web Programming Lecture 14 Slide L14 18
JavaScript Libraries
JavaScript Libraries: Import Statements
JavaScript code may change the HTML markup of an HTML document
Consequently, whenever a browers encounters a script element,
by default, it stops parsing the remaining HTML markup of the page
until that script element has been processed
; poor user experience
‘Safe solution’: Put script elements at the end of the body element
‘Better solution’: Use the async or defer attribute of the script
element to change the default behaviour
< script src =" jsLib1 . js " async > </ script >
< script src =" jsLib2 . js " async > </ script >
Do not wait for the processing of the script elements, fetch and
execute jsLib1.js and jsLib2.js (in parallel) in any order
< script src =" jsLib1 . js " defer > </ script >
< script src =" jsLib2 . js " defer > </ script >
Do not wait, fetch jsLib1.js and jsLib2.js (in parallel), execute in
order after parsing is finished
COMP519 Web Programming Lecture 14 Slide L14 19
JavaScript Libraries
JavaScript Libraries: Example
~ullrich/public_html/sort.js
funct ion b ubble_sort ( array ) {
funct ion swap (i , j) { ... }
... swap (j , j +1) ...
return array
}
example.html
< html lang =" en - GB " >
<head >< title > Sorting example </ title >
< s cript src =" http :// cgi . csc . liv . ac . uk/
ullr ich / sort . js " >
</ script >
</ head >
<body >
<script >
array = [20 ,4 ,3 ,9 ,6 ,8 ,5 ,10];
sorted = bubble _ s o rt ( array . slice (0))
</ script >
</ body >
</ html >
COMP519 Web Programming Lecture 14 Slide L14 20
Further Reading
Revision and Further Reading
Read
Chapter 15: Arrays
of R. Nixon: Learning PHP, MySQL & JavaScript:
with jQuery, CSS & HTML5. O’Reilly, 2018.
Read
Chapter 5: Reference Types: The Array 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
COMP519 Web Programming Lecture 14 Slide L14 21
Further Reading
Revision and Further Reading
Read
Flavio Copes: Efficiently load JavaScript with defer and async. 24 March
2018. https://flaviocopes.com/javascript-async-defer/ (accessed
16 October 2019)
Ravi Roshan: Async Defer: JavaScript Loading Strategies. Medium,
3 January 2019. https://medium.com/@raviroshan.talk/
async-defer-javascript-loading-strategies-da489a0ba47e.
(accessed 16 October 2019)
Mozilla and individual contributors: Window: load event.
MDN Web DOcs, 4 October 2019. https:
//developer.mozilla.org/en-US/docs/Web/API/Window/load_event
(accessed 16 October 2019)
COMP519 Web Programming Lecture 14 Slide L14 22