COMP284 Practical 7
JavaScript (2)
Introduction
• This worksheet contains further exercises that are intended to familiarise you with JavaScript
programming. While you work through the tasks below compare your results with those
of your fellow students and ask for help and comments if required.
• This worksheet can be found at
https://cgi.csc.liv.ac.uk/~ullrich/COMP284/notes/practical07.pdf
and you might proceed more quickly if you cut-and-paste code from that PDF file. Note
that a cut-and-paste operation may introduce extra spaces into your code. It is important
that those are removed and that your code exactly matches that shown in this worksheet.
• The exercises and instructions in this worksheet assume that you use the Department’s
Linux systems to experiment with JavaScript.
If you want to use the Department’s Windows systems instead, then you can do so.
• To keep things simple, we will just use a text editor, a terminal, and a web browser. You
can use whatever text editor and web browser you are most familiar or comfortable with.
• If you do not manage to get through all the exercises during this practical session, please
complete them in your own time.
Exercises
1. Hopefully, so far all your JavaScript code worked without problem. Once you write your
own code, this is not likely to always be the case. If your code contains syntax errors,
you have already seen that the console can give you an indication where those errors are.
But logical errors are harder to find. Your code contains logical errors if the code does
not produce any syntax or runtime errors but produces an incorrect result or incorrect
behaviour. Here we look at two ways that you can use to pinpoint logical errors in the
code.
a. Start a new file js07A.html in your public_html directory with the following content:
JavaScript 07A
Then create a separate file js07A.js in your public_html directory with the following
content:
function random() {
var mode = Math.floor((Math.random()*4)+1)
/* Add debugging code here */
switch (mode) {
case 1: randvar = Math.round(Math.random()*100);
break
case 2: randvar = String(Math.random())
break
case 3: randvar = Math.random()/(Math.random()+1)
break
default: randvar = Boolean(Math.random()+0.5)
break
}
}
b. Save the files and make sure that their access rights are set correctly using the command
chmod u+r,og-rwx $HOME/public_html/js07A.*
(Note: No space after the comma!) You will only have to do so once. File permissions
should not change while you continue to edit the file.
c. Open a web browser and access the URL
https://student.csc.liv.ac.uk/∼/js07A.html
where should be replaced by your departmental user name, and inspect the
output that our JavaScript script has produced. The output might be something like
this:
Random value: (number)0.4064974478835452
Random value: (string)0.0037800505449638866
Random value: (boolean)true
Random value: (boolean)true
Random value: (string)0.4909139084492823
d. Suppose that you are not sure what branch of the switch-statement is executed each
time the function random() is called and you would like to know what the values of the
variables i and mode in each iteration of the for-loop are to figure that out. To get this
information you can add the following debugging code at the point inside the definition
of random() indicated in the code.
console.log("i =",i," mode =",mode)
2
Figure 1: JavaScript Debugger in Google Chrome
e. Save the file, reload jsDemo07B.html in your web browser, then have a look at the
JavaScript console of the web browser. It should contain output like
i = 1 mode = 1 js07A.js:4
i = 2 mode = 2 js07A.js:4
i = 3 mode = 4 js07A.js:4
i = 4 mode = 4 js07A.js:4
i = 5 mode = 2 js07A.js:4
So, console.log wrote its output to the console, not the HTML document, and you can
now see what the values of i and mode are. The number 4 after js07A.js: indicates
that the output was produced by code in line 4 of file js07A.js.
f. Observe that the console.log statement you have added to random() in js07A.js
refers to a variable i that only exists in js07A.html. Why does that work?
g. An alternative or additional facility that you can use to find logical errors in a JavaScript
program is the debugger that browsers like Google Chrome and Mozile Firefox provide.
In the following we focus on Google Chrome. Replace the line introduced in 1d by the
following
debugger
h. Save the file, make sure that the developer tools are already open in the browser, then
reload the file. In the developer tools you should now see the HTML markup and
JavaScript code of the page and the line containing debugger is highlighted (Figure 1).
In the rightmost column, just above the line ‘Debugger paused’ you see a number of
icons that control the debugger [1]. Below that are various panels with additional
information and functionality.
i. We will use one these functions, namely, Watch, that allows us to keep an eye on the
value of a variable or expression. To add a variable that you want to watch, click on the
plus symbol to the right of Watch then type in the name of the variable into the field
that appears. Use this to watch the variables i and mode.
j. Now proceed with the execution of the code. Use the button to ‘resume execution’
of the code. The execution will again stop when it encounters the debugger statement
again which is at the next iteration of the for-loop. Observe how output starts to appear
in the browser window and how the values of the watched variables change.
k. The debugger has a lot of other useful features, for a more comprehensive tutorial on
its use see [1].
2. Let us continue with an exercise related to functions and multi-dimensional arrays in
JavaScript.
3
a. Open a text editor and enter the following JavaScript code:
Practical 7: JavaScript Objects
b. Save the code to a file named js07B.html in $HOME/public_html/. Make sure that the
access rights for the file are set correctly.
c. Open js07B.html in a web browser. Right now the scripts do not do much and the
output you should see is simply
The sum of cells around [1,1] is undefined
4
You can also have a look at the console where you should see that a two-dimensional
array has been created and filled with random natural numbers between 0 and 100.
d. Complete the function showArray with code that displays the content of the two-
dimensional array ar as a two-dimensional HTML table. Each HTML table cell should
contain the co-ordinates of the cell and value in ar stored at those co-ordinates. Here
is an example of what the HTML table should look like:
[0][0] 34 [0][1] 9 [0][2] 40
[1][0] 39 [1][1] 18 [1][2] 74
[2][0] 38 [2][1] 77 [2][2] 1
e. Next, we want to define the function sumAround(). The function takes an array ar and
natural numbers x and y as arguments and should return the sum of the values stored
in ar at co-ordinates ‘surrounding’ (but not including) [y][x]. For [y][x] = [1][1], the
cells ‘surrounding’ [1][1] are ar[0][0], ar[0][1], ar[0][2], ar[1][0], ar[1][2], ar[2][0], ar[2][1],
ar[2][2]. The return value of sumAround(ar,1,1) for the array ar above should be 312.
For [y][x] = (2, 2) the cells ‘surrounding’ [2][2] are just [1][1], [1][2], [2][1]. The return
value of sumAround(ar,2,2) for the array ar above should be 169.
f. Finally, we develop the function maxAround(). The function takes an array ar and
natural numbers x and y as arguments and should return the maxium value stored in
ar in cells ‘surrounding’ (but not including) [y][x].
For the array ar above and co-ordinates [y][x] = [0][1], maxAround(ar,1,0) returns 74.
For the array ar above and co-ordinates [y][x] = [2][0], maxAround(ar,0,2) returns 77.
3. In the lectures we have also considered various aspects of objects in JavaScript, in par-
ticular, the way instance variables and ‘class’ variables are declared and how these can be
made public or private.
The following exercise is intended to reinforce those considerations.
a. Open a text editor and enter the following JavaScript code:
Practical 7: JavaScript Objects
This code will serve as test code for Exercise 3c.
b. Save the code to a file named js07C.html in $HOME/public_html/. Make sure that the
access rights js07C.html are set correctly.
c. We want to define an employee object. To keep the exercise simple, we assume that the
only attributes of an employee are a name and a salary. The first should be public, the
second private. In addition, we need a method to obtain information on an employee’s
salary as well as a method that allows us to change it. Finally, we want to keep track
of how many employees there are in total and we want to keep that number private.
The total number of employee’s should be automatically incremented each time a new
employee object is created.
Create a constructor for employee objects that satisfies these requirements and add it
to the head section of js07C.html.
d. Test your definition of the employee constructor by opening js07C.html in your web
browser and observing that the output is as expected.
e. Since the total employee count is not really an attribute of a particular employee, it is a
bit odd that we obtain that count by using an expressions like e[1].employeeCount().
Is it possible to define employeeCount() in such a way that we could use the expression
Employee.employeeCount() instead? If so, modify your code accordingly and test your
solution by replacing
document.writeln("Employees: "+e[1].getEmployeeCount()+
"
") // prints Employees: 3
with
document.writeln("Employees: "+Employee.getEmployeeCount()+
"
") // prints Employees: 3
and checking that you get the correct output after you have saved the file and refreshed
the page in the browser.
f. Being able to ‘create’ new employees is obviously nice, but sometimes we also have to
‘delete’ an existing employee.
Can we extend our definition of Employee by a method remove that deletes a particular
employee object and at the same time decrements the total employee count? If so,
modify your code accordingly and test your solution by adding the code
e[2].remove()
6
document.writeln("Employees: "+Employee.getEmployeeCount()+
"
") // prints Employees: 2
and checking that you get the correct output after you have saved the file and refreshed
the page in the browser.
Hint: Refer to
http://stackoverflow.com/questions/684575/how-to-quickly-clear-a-javascript-object
g. We want to prompt the user to enter a new salary for one of our employees. Add the
following code to the body section of js07C.html (after the already existing code):
do {
string = prompt("Enter a new salary for "+
e[0].name+"?",e[0].getSalary())
newSalary = parseInt(string)
} while (isNaN(newSalary) || newSalary <= 0)
e[0].setSalary(newSalary)
alert("The new salary for "+e[0].name+" is "+
e[0].getSalary())
Save the file. Clear the output shown in the error console, then refresh the page in
your web browser. Check that the code is working correctly. If it does you will first see
a dialog box that prompts you to enter a new salary for ’Hal Smith’ and then another
dialog box will inform you what the salary of ’Hal Smith’ has been changed to which
should be the new salary that you have just entered.
h. Obviously, that dialog would be much more useful if you could change the salary of an
employee whom you specify by providing his/her name.
As a first step you would need an additional dialog box that prompts the user for
the name of an employee. Then you would need to define a function that given a
name finds which of the employee objects in the array e stores data for an employee
with that name and returns that particular object; for comparison of names you could
either use string equality or a regular expression search. Finally, you need to execute
that function for the name that the user entered, and pass the returned object to the
code in the previous step.
Implement that functionality and test it by entering various names that do or do not
concur with the names for one of the existing employees and change their salaries.
References
[1] Kayce Basques. Tools for Web Developers: Get Started with Debugging JavaScript in Chrome
DevTools. Google. 22 August 2018. URL: https://developers.google.com/web/tools/
chrome-devtools/javascript/ (accessed 10 October 2018).
7