Topic 7
JavaScript for Client-side Web Development
Introduction
This Topic explores the basics of JavaScript as a client-side scripting language. Unfortunately, you
cannot use PHP for the client side development so learning JavaScript is a must. As this Topic is an
introduction to programming with JavaScript, it is not expected that you will feel totally comfortable
with the language after this topic. However, you should understand the structure of the language,
recognise the language terminologies and syntax, know where and how to add script(s) to an HTML
file. Ultimately you will be able to manage and manipulate scripts for use in your Web pages.
The practical exercises for this Topic work through the code introduced in the theory. The exercise
will allow you to incorporate JavaScript into your assignment.
As always, the study guide only provides you the key points you should have learned in each topic.
Reading the study guide material is not enough. It is essential that you practise your programming
skills by completing all activities in the study guides.
Objectives
On completion of the Topic, you should be able to:
Discuss the purpose of JavaScript as a client-side scripting language
Explain the execution mechanism of JavaScript as a client-side scripting language
Understand the structure and syntax of JavaScript
Recognise and use JavaScript objects, properties and methods
Use JavaScript to perform some simple tasks based on existing scripts
JavaScript as a Client-side Scripting Language
Overview of JavaScript
JavaScript was developed by Netscape in partnership with Sun Microsystems in 1995. The
programming language existed under another name, LiveScript, before this time and was owned
exclusively by Netscape. A language standard for JavaScript was developed in the late 1990s by
ECMA (European Computer Manufacturers Association), which was approved by the ISO
(International Standards Organisation).
JavaScript is a scripting language unlike HTML which is a mark-up language. JavaScript is designed
to improve user interactivity and experience in using web-based information systems including web
applications, which cannot be provided by HTML alone. Client-side JavaScript helps improving
interactions with users via handling users input locally, manipulating HTML documents to reflect
the communication context and providing instant feedback to users. JavaScript also smoothens the
PROG2002
CSC10217 Topic 7 - JavaScript for Client-side Web Development
Page 2
client-server interaction via a technology called AJAX (Asynchronous JavaScript And XML). The
technology enables asynchronous updates of client side web pages, which significantly improves the
user experience.
Client-side JavaScript is mainly used to create dynamic user interfaces, perform client-side input
validation and carry out simple computation tasks. Recently AJAX has been used in client-server
communication of modern web applications, which implement MVC design pattern.
JavaScript can be used as both client-side and server-side scripting language i.e. it can be used in
place of PHP at the server side. However, JavaScript is much more popular as a client-side language
mainly due to historical reasoning. Client-side JavaScript was developed in 1995 while the language
was first used as a server side language in 2009 with the introduction of NodeJS.
JavaScript Execution Mechanism
Like PHP, JavaScript is an interpreted language i.e. the code is executed top-down line-by-line by
an interpreter without compilation.
Server-side JavaScript code is executed on the server side by a server-side JavaScript interpreter.
The most popular JavaScript interpreter today is NodeJS. NodeJS was originally written by Ryan
Dahl in 2009. The initial release supported only Linux and Mac OS X but now can run on Windows
OS.
Client-side JavaScript code is embedded into an HTML page. Embedded can also mean placed in an
external file then linked into a HTML document. JavaScript code is interpreted and executed directly
by web browsers without an external JavaScript interpreter. For a browser to interpret JavaScript,
settings must be enabled in the browser options.
To embed JavaScript code in an HTML document use the pair of <script></script> tags:
JavaScript is flexible in that the JavaScript code can be included anywhere in an HTML document.
However the most preferred ways to include JavaScript in an HTML file are as follows −
Script in <head>...</head> section.
Script in <body>...</body> section.
Script in <body>...</body> and <head>...</head> sections.
Script in an external file and then included in <head>...</head> section.
Since HTML and JavaScript code is loaded and interpreted top-down, the location of the code does
affect the execution result. For example, the code may fail to execute if it refers to an HTML element,
PROG2002
CSC10217 Topic 7 - JavaScript for Client-side Web Development
Page 3
which has not been loaded at the time the code is executed. However, if the code needs to modify
the HTML code before the document is displayed, it has to be executed first.
In this case, if JavaScript code is shared by multiple documents, it is a good practice to place the
script in a dedicated file and load the file in the document head i.e. between <head></head> tags.
This is done using the src parameter of the <script> tag as in the following example:
Language Syntax and Structure
Basic Structure and Syntax
JavaScript likes any programming language has its own syntax, data types and operators. You will
need to familiarise yourself with JavaScript syntax, data types and operators. Use the following
online resource to study the language structure (the JavaScript Basics Tutorial section):
https://www.tutorialspoint.com/javascript/index.htm
JavaScript document objects
Note that unlike PHP, JavaScript is not a class-based object oriented programming language.
However, it is an object based programming language and it works with objects. The most important
object JavaScript works with is the document object. This is a built-in object that represents the
HTML document, in which the executing script is embedded. Using document object and its
methods, you can manipulate the HTML document. For example, the following JavaScript code
writes some text to the document (and therefore erase all existing content):
document.write("some text");
You also can use the document.write methods to write HTML directly on a web page. For example:
document.write("<h1>Welcome to WebDev-2</h1>");
A text string can be enclosed within either double (") or single (') quotation marks. This allows
you to write a text string that includes attribute values. Consider the following:
document.write('<td class="calendar_head" colspan="7">');
The command will write a table cell tag to the Web page.
<td class="calendar_head" colspan="7">
NOTE: Remember that JavaScript is case-sensitive. Also remember that every JavaScript command
line ends with a semi-colon (;). In some situations, the semi-colon is optional, but it is a good idea
to use it to make your code easier to follow and interpret.
You will study more about the document object in the next topic.
Alerts, confirmations and prompts
JavaScript provides a set of built-in functions to communicate with users using GUI. The built-in
PROG2002
CSC10217 Topic 7 - JavaScript for Client-side Web Development
Page 4
functions include alert(), confirm() and prompt():
alert("Hello from JavaScript"); var answer;
answer = confirm("Continue
with this topic?");
document.write(answer);
var city;
city = prompt("What is
the name of your city?",
"City?");
document.write(city);
An alert interaction displays a simple dialog box with a message. The dialogue has a single button
labelled “OK” that the user must click to continue. An alert is launched with the global function
alert() as in the following example.
alert("Hello from JavaScript");
This launches a dialog box with the message “Hello from JavaScript” and waits for the user to click
the “OK” button before continuing.
An alert can display up to three lines of text. This means you can pass text to the alert() function
with up to two newline character (\n) in the string. For example, if you wanted to display each of
the three words in the above message on different lines the function call would be:
alert("Hello\nfrom\nJavaScript");
The second type of interaction is where a user is asked for a yes/no response. The confirm dialogue
prints a message and displays two buttons labels “OK” and “Cancel”. The user must click one of
these two buttons to continue. This is implemented with the global function confirm() which
returns a Boolean true value if the user clicks “OK” or a false if the user click “Cancel”. For example,
if you wanted to ask “Continue with this topic?” and receive a response, you would write:
answer = confirm("Continue with this topic?");
Notice how you assign the result of the confirm dialog box to the variable answer in this case.
The third type of dialog is where the user is prompted for text input. This interaction prints a message
and requests a text field response from the user. It displays two buttons, an “OK” and a “Cancel”
button. It also allows default text to be specified. The prompt dialog is produced by the prompt()
global function as in the following example:
city = prompt("What is the name of your city?", "");
Notice how there are two parameters to this function. The first is the prompt to be displayed and the
second is the default text to place in the text field. If the user clicks “OK” or just types the Enter key
then the string is returned. If the user clicks the “Cancel” button then null is returned.
JavaScript functions
Like PHP, JavaScript supports defining and using functions as a way to package JavaScript code so
it can be used in different places. By using the function name in a statement you can execute the
function’s code. In addition, you can pass parameters to a function so you can modify its behaviour.
You can also return a value from the function to be used where the function was called.
JavaScript supports a very flexible way of declaring and using functions compared to PHP and other
programming languages. A JavaScript function can be declared in the following ways:
PROG2002
CSC10217 Topic 7 - JavaScript for Client-side Web Development
Page 5
function function-name (arg1, arg2, ...){
statements;
}
var x = function (arg1, arg2, ...) {
statements;
};
var x = new Function(arg1, arg2..., "Function Body");
So an example of a simple function to print a simple “hello” message is:
function hello() {
document.write("hello<br>");
}
var hello = function () {
document.write("hello<br>");
}
The format of the declaration is the same as described before using the <script> tag to surround
the JavaScript declarations. So, a complete HTML file to define and call the above function would
look like the following:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf8”>
<title> The Javascript Functional Hello</title>
<script language="javascript">
<!—
function hello() {
document.write("hello<br>");
}
// -->
</script>
</head>
<body>
<script language="javascript">
<!--
hello();
// -->
</script>
</body>
</html>
The final attribute of functions is the optional returned value. This is achieved by placing a return
statement in the function body. The format of the return statement is:
return value;
When a return statement is encountered the function is immediately terminated and the value is
returned to the point where the function was called. To demonstrate this you can define a function
that returns the difference between two numbers as follows:
function diff(x, y) {
var d = x-y;
PROG2002
CSC10217 Topic 7 - JavaScript for Client-side Web Development
Page 6
if (d < 0)
return y-x;
else
return d;
}
This function has two parameters x and y and returns the positive difference between the two
numbers.
JavaScript does not check if the number of parameters in the formal definition matches the number
of parameters in the actual function call. Any extra parameters in the function call are ignored and
any extra parameters in the formal definition (actual call has too few parameters) are assigned an
undefined value. The property arguments.length contains the number of parameters used in a
function call and each one can be accessed using an array index, e.g. arguments[0].
JavaScript objects
An object in JavaScript is a collection of named properties. A property can be either data or a method.
The data properties (called just “properties”) can either be a primitive data type or a reference to
another object. The method properties (called “methods”) are JavaScript functions that execute some
JavaScript code. To access properties or methods in an object we use the common dot-notation:
object_name.property_name
For example, to access the property named status of the object named button1 we code:
button1.status
Since properties can be objects that have properties as well, we sometimes need to name a series of
objects to access the property we require. To do this we apply the ‘.’ operator in series. For example,
suppose the above object was itself a property of the object named group2, we would access the
button1 status as follows:
group2.button1.status
Members are functions so we can also use parameters when accessing them. If there are no
parameters then we use a pair of empty parentheses “()” appended to the method name.
The following are examples of method access in JavaScript:
frame2.setSize(20,100);
button1.reset();
Properties can be added and removed from objects at any time. This is quite different from object-
oriented languages, which require inheritance to add or change properties and usually prevent
properties from being deleted.
JavaScript instantiates an undefined object using the following syntax:
var my_object = new Object();
Properties and methods can be assigned to the object after the new call.
var person = new Object();
person.name = “Some name”;
Built-in objects are created by calling the object constructor methods. For instance, the constructor
PROG2002
CSC10217 Topic 7 - JavaScript for Client-side Web Development
Page 7
for arrays is named Array.
var my_array = new Array();
JavaScript can also create an object using an object literal. For instance:
var person = {firstName:"John", lastName:"Doe", age:50};
JavaScript has predefined reference variable this for accessing the object and its properties. When
the constructor is called, this is a reference to the newly created object. For instance:
var person = {
firstName: "Penelope",
lastName: "Barrymore",
fullName: function () {
console.log(this.firstName + " " + this.lastName);
// We could have also written this:
console.log(person.firstName + " " +
person.lastName);
}
}
Arrays
In JavaScript arrays are objects that have some special functionality and may also be describes as
an ordered collection of values referenced by a single variable name. The syntax for creating an array
variable is:
var variable = new Array(size);
Where variable is the name of the array variable and size is the number of elements, or
distinct values, in the array.
// nested_arrays.js -- An example illustrate an array of arrays
// Create an array object with three arrays as its elements
var nested_array = [[2, 4, 6],
[1, 3, 5],
[10, 20, 30]
];
// Display the elements of nested_list
for (var row = 0; row <= 2; row++) {
document.write("Row ", row, ": ");
for (var col = 0; col <=2; col++)
document.write(nested_array[row][col], " ");
document.write("<br>");
}
Arrays in JavaScript are quite different to many other languages because of the dynamic typing of
JavaScript. They also have an Array wrapper class with a large collection of member functions that
can sort and otherwise manipulate the order and content of arrays.
To create an array:
var variable = new Array( );
Where variable is the name of the array variable.
PROG2002
CSC10217 Topic 7 - JavaScript for Client-side Web Development
Page 8
To populate an array:
variable[i] = value;
Where variable is the name of the array variable, i is the ith element of the array, and value is the
value of the ith element.
OR
var variable = new Array(content);
Where content is a list of the array element enclosed in quotes and separated by commas.
Another useful feature is the use of pattern matching. A pattern is a regular expression
which can be used to search strings, edit strings or check strings for correct format. Regular
expressions themselves are strings that can have complicated formats.
Rules to remember for JavaScript
JavaScript is case sensitive.
String literals can be enclosed in single quotes (') or double quotes (").
Special characters are escaped with a ‘\’ character as in C and Java. For example, ‘\n’
represents a newline character and ‘\t’ represents a tab.
The string delimiter can be included in the string by using an escape ‘\’ (\' or \") and the
escape character itself can be included by using ‘\\’.
Quotes are required around values.
JavaScript has a distinct format that must be adhered to – placing a line break in the wrong
place will cause an error.
Variable names can start with any character except a numeric digit or most special
characters. The characters underscore ‘_’ and dollar sign ‘$’ can be used anywhere in a name
and decimal digits ‘0’..’9’ can be used anywhere after the first character.
You can use your Web browser to troubleshoot JavaScript. (see debugging section 4.14 of
text for How to instructions In Firefox, IE and Chrome)
External JavaScript files are typically saved with a .js extension.
Each JavaScript statement ends with a semicolon (;).
Activity 4.1
Complete the following quizzes:
https://www.w3schools.com/quiztest/quiztest.asp?qtest=JavaScript
https://www.thejsquiz.com/ (beginners)
Activity 4.2
Write JavaScript code to sort the following list of movies in ascending order by title and print the
result out in a HTML table with the movie name and its index:
movies_list = (Conspiracy Theory, Six Degrees of Separation, The Book of Life, Sleeping
with the Enemy, Mona Lisa Smile)
Activity 4.3
PROG2002
CSC10217 Topic 7 - JavaScript for Client-side Web Development
Page 9
Complete at least 10 exercises (or more if possible) in https://www.w3resource.com/javascript-
exercises/javascript-basic-exercises.php. Try yourself first before looking at the provided solutions.
Assignment advice
In this week you start working on version-2 of the movie_zone application. You will work on
completing the View module by replacing plain text output functions with html formatted text
outputs. You will also need to start building the user interface for the application. Note that you
need place each input form in a separate HTML document so they can be tested separately.
Summary
This Topic has familiarised you with the basic syntax of JavaScript and the general capabilities of
the language. You should know by now how to embed JavaScript code in HTML documents and use
JavaScript to perform some simple tasks at the client side.
In the next topic, we will look at how to use JavaScript to process HTML forms, perform data
validation and manipulate the HTML document.
References
JavaScript Tutorial. [ONLINE] Available at: https://www.tutorialspoint.com/javascript/index.htm.
[Accessed 09 April 2018].
JavaScript Tutorial. [ONLINE] Available at: https://www.w3schools.com/js/default.asp. [Accessed
09 April 2018].
PROG2002