Chapter 03-Client-Side Scripting Languages
Chapter 03-Client-Side Scripting Languages
3.1. INTRODUCTION
This chapter provides an introduction to client-side scripting languages, with a focus on JavaScript. JavaScript is
the most common language used in effective client-side programming and it is the basic language that one has to
fully understand during this chapter. By the end of this chapter, students will have a solid understanding of
JavaScript programming concepts, data structures, libraries and the DOM (Document Object Model (DOM).
The most popular client-side scripting languages are JavaScript, TypeScript (1995), VBScript (1996), JQuery
(2006) and PureScript (2013). These languages offer several advantages for web development including:
▪ Enhanced User Experience and making websites more engaging and user-friendly,
▪ Reduced Server Load by performing tasks on the client-side,
▪ Enable web pages to respond quickly to user actions without requiring a round trip to the server,
▪ Provide flexibility and ease of development
▪ Supported by all major web browsers, making them highly compatible across different platforms,
▪ They have a vast ecosystem with active communities, which means developers have access to abundant
resources, tutorials, forums, and libraries.
1|Page
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES
updates to web pages without requiring constant communication with the server. Key features and characteristics
of JavaScript include:
▪ HTML Integration: JavaScript can be embedded directly within HTML code using <script> tags. It can
manipulate and modify the content and structure of a webpage.
▪ Event Handling: JavaScript can respond to user actions such as clicks, keyboard inputs, and mouse
movements, allowing developers to create interactive interfaces.
▪ Animations and Effects: JavaScript can be used to create animations, transitions, and effects that
enhance user experience by providing visual feedback.
▪ AJAX (Asynchronous JavaScript and XML): AJAX enables data to be fetched from the server in the
background without requiring a full page reload. This contributes to smoother and more responsive web
applications.
▪ Web APIs: Modern browsers provide various APIs (Application Programming Interfaces) that
JavaScript can access to perform tasks like manipulating the browser history, working with multimedia,
handling geolocation, and more.
▪ Libraries and Frameworks: JavaScript has a rich ecosystem of libraries and frameworks, such as
jQuery, React, Angular, and Vue.js, that provide pre-built components and tools for building complex
web applications more efficiently.
▪ Cross-Browser Compatibility: JavaScript is supported by all major web browsers, making it a reliable
choice for creating web content that works across different platforms.
▪ Server-Side JavaScript: While JavaScript is mainly used on the client side, it can also be used on the
server side with technologies like Node.js. This allows for building server-side applications using the
same language.
2|Page
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES
To ensure that JavaScript could be implemented consistently across different browsers, Netscape submitted the
language to the European Computer Manufacturers Association (ECMA) for standardization. In 1997,
ECMAScript was established as the official standard for JavaScript. Since then, new versions of ECMAScript
have been released regularly, each introducing new features and improvements.
JavaScript's versatility and ability to run on the client-side (in web browsers) as well as the server-side (with
Node.js1) contributed to its rapid growth in popularity. Developers began using JavaScript for more complex
tasks, such as form validation and image sliders, making web pages more interactive and user-friendly.
As JavaScript gained traction, Microsoft developed its own implementation called "JScript" for Internet Explorer.
This led to a period known as the "Browser Wars" in the late 1990s and early 2000s, where different browsers
had their own versions of JavaScript with varying degrees of compatibility.
With the increasing complexity of web applications, developers sought ways to make the JavaScript code more
manageable and maintainable. This led to the emergence of popular JavaScript libraries and frameworks like
jQuery2, React3, and Vue.js4, which simplified web development and promoted best practices.
Today, JavaScript is not only limited to the browser but is also used on the server-side with Node.js, allowing
developers to create full-stack applications using a single language. It has become an integral part of the web
development landscape, driving innovation and shaping the modern web experience.
However, being executed on the client-side, JavaScript has some security considerations, such as preventing
cross-site scripting (XSS) attacks and ensuring the secure handling of user data.
The following example illustrates what you can do with JavaScript. It shows an example of a flashing grid of
coloured squares. In this example, a JavaScript function changes the colour of a randomly chosen square in the
grid every second. You can find the source code of this example is available in the exercises section.
▪ Internal JS: We can add JavaScript directly to our HTML file by writing the code inside the <script>
tag. The <script> tag can either be placed inside the <head> or the <body> tag according to the
requirement.
<script type="text/javascript">
alert ("This alert box was called with the onload event");
</script>
1
Node.js (https://nodejs.org/en) is an open-source server environment that allows you to run JavaScript on the server. It runs on various
platforms (Windows, Linux, Unix, Mac OS X, etc.).
2
JQuery (https://jquery.com/) is a fast, small, and feature-rich JavaScript library.
3
React (https://react.dev/), also known as React.js or ReactJS, is a free and open-source front-end JavaScript library for building user interfaces
based on components.
4
Vue.js (https://vuejs.org/) is an open-source model–view–view model front end JavaScript library for building user interfaces and single-
page applications. It provides a declarative and component-based programming model that helps you efficiently develop user interfaces, be
they simple or complex.
3|Page
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES
▪ External JS: We can write JavaScript code in other files having an extension.js and then link this file
inside the <head> tag of the HTML file in which we want to add this code.
x = 5; // automatically declared
y = 6; // automatically declared
z = x + y; // z stores the value 11
let w=y-x // w stores the value 1
let age=30; // age value can be changed
const pi = 3.14; // pi value cannot be changed
var r=pi*(x+y); // r stores 34.54 and this value can be changed
Note 1: It is considered good programming practice to always declare variables before use. Thus, it is better to
always declare variables. Only use var if you MUST support old browsers and use const if the value or the type
should not be changed (e.g., Arrays, function, object). let can be used if you cannot use const.
Note 02: It is also important to note that all JavaScript variables must be identified with unique names called
identifiers. They can be short names (like x and y) or more descriptive names (age, sum, total, etc.).
The general rules for constructing names for variables (unique identifiers) are:
1) Names can contain letters, digits, underscores, and dollar signs.
2) Names must begin with a letter and they can also begin with dollar ($) and underscore (_).
3) Names are case sensitive (y and Y are different variables).
4) Reserved words (like JavaScript keywords like @, #, %) cannot be used as names.
Note 03 (JavaScript comments): they can be used to explain JavaScript code, and to make it more readable.
They can also be used to prevent execution, when testing alternative code.
▪ Single Line Comments : Single line comments start with //. Any text between // and the end of the line
will be ignored by JavaScript (will not be executed).
4|Page
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES
▪ Multi-line Comments: Multi-line comments start with /* and end with */. Any text between /* and */
will be ignored by JavaScript.
/*
The code in this example:
Shows how you can use a
Single line comment and, a
Multi-line comment
*/
let x = 5; // Declare x, give it the value of 5
let y = x + 2; // Declare y, give it the value of x + 2
5|Page
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES
Note 01: In expressions that encompass several arithmetic operations, multiplication (*) and
division (/) have higher precedence than addition (+) and subtraction (-). When using
parentheses, the operations inside the parentheses are computed first. Thus, the precedence can
be changed by using parentheses.
Note 02: Comparison operators are used are used in logical statements to determine equality or difference
between variables or values. JavaScript has a Boolean data type. It can only take the values true or false
values. In javascript, you can use the Boolean () function to find out if an expression (or a variable) is true
or not (The Boolean value of 0 (zero) is false).
Note 03: Logical operators are used to determine the logic between variables: An expression containing
these operator returns either true or false depending upon whether expression results true or false.
Examples:
let name = "Rida"; //string
let age=32; //number
let b=4.55; //number
let c=10e3; //number
let x=false; //boolean
var a; //undefined
var b-null; //Null
let arr=[1,2,3]; //array
let obj={ name: "Rida", age:21}; //object
function fun() { // function
document.write("Hello")
}
6|Page
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES
In JavaScript, we can know the data type of a variable using the ‘typeof’ operator.
<!DOCTYPE html>
<html lan="en">
<head>
<meta charset="UTF-8">
<title>My Form</title>
</headf>
<body bgcolor="bisque">
<h1> Javascript Typeof </h1>
<script type="text/javascript">
let name = "Rida";
let age=32;
document.write(typeof(name)+ " ");
document.write(typeof(age))
</script>
</body>
</html>
Example:
<!DOCTYPE html>
<html lan="en">
<head>
<meta charset="UTF-8">
<title>My Form</title>
</head>
<body bgcolor="bisque">
<h1> Javascript output </h1>
<script type="text/javascript">
7|Page
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES
Examples
The switch statement is used to select one of many code blocks to be executed.
▪ The switch expression is evaluated once.
▪ The value of the expression is compared with the values of each case.
▪ If there is a match, the associated block of code is executed.
▪ If there is no match, the default code block is executed.
Break statement: when JavaScript reaches a break keyword, it breaks out of the switch block. This will stop
the execution inside the switch block. It is not necessary to break the last case in a switch block. The block breaks
(ends) there anyway. If you omit the break statement, the next case will be executed even if the evaluation does
not match the case.
The default keyword can be used to specify the code to run if there is no case match:
Example: This example uses the weekday number to calculate the weekday name. For that we use the predefined
javascript method getDay() of the instance Date(). This method returns the weekday as a number between 0
and 6 (Sunday=0, Monday=1, Tuesday=2 ..).
8|Page
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES
3.3.9. Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in loops. It makes the
code compact. It is mostly used in array. JavaScript supports different kinds of loops:
▪ for - loops through a block of code a number of times
▪ while - loops through a block of code while a specified condition is true
▪ do/while - also loops through a block of code while a specified condition is true
Examples
// increases i value each time the code block in the loop has been executed:
for (let i = 0; i < 5; i++) {
text = "The number is " + i + "<br>";
document.write(text);
}
9|Page
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES
As you can see in the example, functions can be used the same way as we use variables, in all types of formulas,
assignments, and calculations. So, instead of using a variable to store the return value of a function, you can use
the function directly, as a variable value.
Local Variables: Variables declared within a JavaScript function, become LOCAL to the function and can only
be accessed from within the function.
// Function is called, the return value will end up in x (x=12)
let x = max(20, 5);
document.write("the maximum is"+ x);
// Function declaration.
function max(num1, num2) {
let result; //result is a local variable to the function max
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
10 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES
Object Definition (declaration): Objects are variables too. But objects can contain many values. For example,
the code below assigns many values (Fiat, 500, white) to the object variable named car. It is a common practice
to declare objects with the const keyword.
// object declaration:
const car = {type:"Fiat", model:"500", colour:"white"};
Object Methods: Methods are actions that can be performed on objects and they are stored in properties as
function definitions. In the example below, the method fullName returns the full name of a person.
In the example above, the keyword this refers to the person object. So, “this.firstName” means the
“firstName” property of person and “this.lastName” means the “lastName” property of person.
Accessing object properties and methods: You can access object properties in two ways, as shown in the
example bellow. If you access a method without the () parentheses, it will return the function definition:
Note: when a JavaScript variable is declared with the keyword " new", the variable is created as an object, as
shown in the examples bellow. But it is better to avoid String, Number, and Boolean objects because they may
complicate your code and slow down execution speed.
Exercise: Create an array of objects, where each object describes a book and has properties for the title (a string),
author (a string), and alreadyRead (a boolean indicating if you read it yet). Then, iterate through the array of
books, and for each book, display the book title, book author and whether you read it yet or not.
Title author alreadyRead
Solution:
11 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES
var books = [
{title: 'The Design of EveryDay Things',
author: 'Don Norman',
alreadyRead: false
},
{title: 'The Most Human Human',
author: 'Brian Christian',
alreadyRead: true
}];
3.3.12. Arrays
The Array object, as with arrays in other programming languages, enables storing a collection of multiple items
under a single variable name, and has members for performing common array operations. In JavaScript, arrays
aren't primitives but are instead Array objects with the following core characteristics:
▪ They are resizable and can contain a mix of different data types. (When those characteristics are
undesirable, use typed arrays instead.)
▪ They are not associative arrays and so, array elements cannot be accessed using arbitrary strings as
indexes, but must be accessed using nonnegative integers (or their respective string form) as indexes.
▪ They are zero-indexed: the first element of an array is at index 0, the second is at index 1, and so on, and
the last element is at the value of the array's length property minus.
▪ Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.
Examples of main operations in Javascript arrays:
Note: the full array can be accessed by referring to the array name. The JavaScript method toString() converts
an array to a string of (comma separated) array values.
12 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES
<p id="demo"></p>
<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
Tow-Dimensional array: A two-dimensional array in Javascript can be thought of as an array of arrays. It can
be created using the new keyword or with nested array literals as shown in the example below:
Array Properties and Methods: The real strength of JavaScript arrays are the built-in array properties and
methods. The table below present examples of the most important methods and properties of Javascript arraies.
Here are some examples of some array properties and methods.
1) The length property returns the length (size) of an array.
2) The method toString() converts an array to a string of (comma separated) array values.
3) The pop() method removes the last element from an array.
4) The push() method adds a new element to an array (at the end).
5) The shift() method removes the first array element and "shifts" all other elements to a lower index.
6) The unshift() method adds a new element to an array (at the beginning), and "unshifts" older
elements:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<p id="demo"></p>
<script type="text/javascript">
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let size = fruits.length; //Result size=4
document.write("Size= "+ size);
document.getElementById("demo").innerHTML = fruits.toString();
</script>
<p id="demo1"></p>
<p id="demo2"></p>
<script type="text/javascript">
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits.pop();
document.getElementById("demo2").innerHTML = fruits;
13 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES
let fruit = fruits.pop(); //returns the value that was "popped out":
</script>
<p id="demo3"></p>
<script type="text/javascript">
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
document.getElementById("demo3").innerHTML = fruits;
let length = fruits.push("Kiwi"); //length size=5
document.write("length= "+ lenght);
</script>
<p id="demo4"></p>
<script type="text/javascript">
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
document.getElementById("demo4").innerHTML = fruits;
let fruit = fruits.shift(); // Returns the value that was "shifted out":
document.write("fruit shifted out= "+ fruit);
</script>
<p id="demo5"></p>
<script type="text/javascript">
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");
document.getElementById("demo5").innerHTML = fruits;
fruits.unshift("Lemon"); // Result 5
</script>
</body></html>
14 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES
1- Adding properties and methods to an object: In javascript, you can easily add new properties, or new
methods to an existing object, as shown in the examples below.
//add the property “nationality” to the object person1
person1.nationality = "Algerian";
//add the method name() to the object person1
person1.fullname = function () {
return this.firstName + " " + this.lastName;
};
▪ In the first example, the property “nationality” will be added only to the object person1. Not to
person2. (Not to any other Person () objects).
▪ In the second example, the method “fullname()” will be added only to the object person1. Not to
person2. (Not to any other Person () objects).
2- Adding properties and methods to a Constructor: You cannot add a new property, or a new method, to an
object constructor the same way you add a new property (method) to an existing object. As shown in the example
below, the new property, or method, must be added inside the constructor function.
//adding a new property (nationality) and a new method (fullName) to the
constructor Person()
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.nationality = "Algerian";
this.fullName = function() {
return this.firstName + " " + this.lastName;
};
}
3- JavaScript Object Prototypes: All JavaScript objects inherit properties and methods from a prototype. In
this context, the Object.prototype is on the top of the prototype inheritance chain. Date objects, Array
objects, and Person objects inherit from Object.prototype.
The JavaScript prototype property allows you to add new properties to object constructors. It also allows you
to add new methods to objects constructors, as shown in the examples below.
15 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES
// constructor Person()
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Exercise: Write a JavaScript program to get the volume of a cylindrical with four decimal places using object
constrictors and the prototype property (volume=Cylindrical hight *PI*radios2).
<!DOCTYPE html>
<html>
<body>
<h1>Volume of a Cylinder</h1>
<script type="text/javascript">
//function constructor
function Cylinder(cyl_height, cyl_diameter) {
this.cyl_height = cyl_height;
this.cyl_diameter = cyl_diameter;
}
// Add the method Volume to the constructor Cylinder with prototype
Cylinder.prototype.Volume = function () {
var radius = this.cyl_diameter/2;
return this.cyl_height * Math.PI * radius * radius;
};
//create new object
var cyl = new Cylinder(7, 4);
// Volume of the cylinder with four decimal places.
alert('volume =', cyl.Volume().toFixed(4)); // volume =87.9646
</script>
</body></html>
4- Built-in JavaScript Constructors: In JavaScript, there are several built-in constructors that allow you to
create objects of various types. The examples below show the most important JavaScript built-in constructors for
native objects. Although these constructors exist, it is recommended to use primitive data types where possible,
because they may complicate your code and slow down execution speed.
// Built-in Constructors
var a = new Object();
var b = new String();
var c = new String('Ali') \\ similar to var c='Ali';
var d = new Number();
var e = new Number(25); \\ similar to var e=25;
var f = new Boolean();
var g = new Boolean(true); \\ similar to var g=true;
16 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES
5- Date object: At times you there will be a need to access the current date and time and also past and future
date and times. In Javascript, we can create instances of the Date built-in object with the new keyword and the
Date’s constructors. Current date and time can be retrieved as shown below:
// Current date and time
var today =new Date();
After running the code, you get the full current date and time of your system as shown below.
Example: Write a JavaScript program to display the current date in the same format as below:
<!DOCTYPE html>
<html>
<body>
<h1>Volume of a Cylinder</h1>
<script type="text/javascript">
function myDate() {
weekdays = new Array ("Monday","Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday", "Sunday");
date_day = new Date();
d=weekdays[date_day.getDay()];
if (date_day.getDate()<10)
{n="0"+ date_day.getDate()}
else
{n=date_day.getDate()};
if (date_day.getMonth()+1<10)
{m="0"+ (date_day.getMonth()+1)}
else {m= date_day.getMonth()+1};
y= date_day.getFullYear();
today_date="Today date is "+d+" : "+n+" / "+m+" /" +y;
return(today_date);
}
var mydate = myDate();
window.document.writeln ("<br><center>"+"<h3><font color='purple'
size='5'>"+mydate+"</h3></center>");
</script>
17 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES
</body></html>
18 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES
In the second example, we use the innerHTML property of the getElementById method to change the content of
the <p> element with id="demo". The innerHTML property is very useful for getting or replacing the content of
HTML elements.
<!DOCTYPE html>
<html>
<body>
<h1>Accessing elements in an HTML document</h1>
<form action="post">
Enter your name: <input id="textid">
</form>
<p id="demo"></p>
<script type="text/javascript">
var name = document.getElementById("textid");
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body></html>
The second way is to use document object’s forms array property along with the element array property. For
example, you can use the script in the HTML code below for obtaining the address of the textbox in the form.
The main problem of this method is, it becomes difficult to obtain the address of elements when there are multiple
forms in a document or if there are a large number of elements in a form, or if new elements are added to a form.
<!DOCTYPE html>
<html>
<body>
The tired way is by using the name attribute of the HTML elements. The problem with this method is, it does not
work with a group of elements with the same name attribute like a group of checkboxes, or a group of radio
buttons which will have the same value for their name attribute in a form tag.
<!DOCTYPE html>
<html>
<body>
19 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES
The table below lists most commonly used events and their associated tag attributes along with their corresponding
tags in HTML:
Event Tag Attribute Tag Description
change onchange <input> The input element is changed and loses focus
<textarea> The text area changes and loses focus
<select> The selection element is changed and loses focus
click onclick <a> The user clicks on the link
<input> The input element is clicked
Double click ondblclick Most elements The user double clicks the mouse left button
focus onfocus <a> The link acquires focus
<input> The input element acquires focus
<textarea> The text area acquires focus
<select> The selection element acquires focus
keydown onkeydown <body> A key is pressed down
Form elements
keypress onkeypress <body> A key is pressed down and released
Form elements
keyup onkeyup <body> A key is released
Form elements
load onload <body> The document finished loading
mousedown onmousedown Most elements The user clicks the left mouse button
mousemove onmousemonve Most elements The left mouse button is released
mouseover onmouseover Most elements The use moves the mouse cursor on the element
reset onreset <form> The reset button is clicked
select onselect <input> The mouse cursor is moved over the element
<textarea> The text is selected within the text area
submit onsubmit <form> The submit button is pressed
unload onunload <body> The user exists the document
20 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES
In the above code, the event handler func1() is assigned to the event attribute onclick of the button tag
▪ The second way is by assigning the event handler to the event property of the element as shown below:
document.getElementById(ID-of-element).onclick=func1;
In the above code, the event handler func1() is assigned to the event attribute onclick of the button tag
<body>
<form id="loginForm" action="next.html" onsubmit="checkData()">
Username: <input type="text" id="txtuser"><br/>
Password: <input type="pass" id="txtpass"><br/>
<input type="submit" value="Submit">
<input type="reset" value="Clear">
</form>
</body></html>
21 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES
Explanation: The general validation process is to check whether the user input matches the requirements. If it
matches, return true which will make the browser shift the control to the page mentioned in the action attribute of
the form tag. Otherwise display appropriate error message and return false which will make the control stay in the
current page.
3.8. EXERCISES
Exercise 01: Write a JavaScript program that calculates the sum, difference, product, and quotient of two integer
numbers. Then, add this program to an HTML document that prompts the user for two numbers, calculates the
sum, difference, product, and quotient, and then displays the results.
Exercise 02: Input two numbers and perform arithmetic action using Select option as in the figure below.
Exercise 03: Write a JavaScript program that checks if an integer number is between 10 and 20 (inclusive) or if
it is greater than 100.
Exercise 04: Write a JavaScript program that compares two numbers and logs whether they are equal, not equal,
greater than, or less than.
Exercise 05: Write a JavaScript program that finds the maximum of three numbers.
Exercise 06: Write a JavaScript program that takes a student's numerical grade as input and outputs their
corresponding letter grade according to the following scale (The grade value is provided by the user.):
▪ A: 90-100
▪ B: 80-89
▪ C: 70-79
▪ D: 60-69
▪ F: Below 60.
Note: give two versions of the program, the first one is with the if… elseif statement and the second one is with
the switch statement.
Exercise 07: Write a JavaScript program that checks if a given character is a vowel or a consonant.
22 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES
Exercise 08: Write a JavaScript program where the program takes a random integer between 1 and 10, and the
user is then prompted to input a guess number. The program displays a message "Good Work" if the input matches
the guess number otherwise "Not matched, Try another number".
Exercise 09: Write a JavaScript program to remove a character at the specified position in a given string and
return the modified string.
Exercise 10: Write a JavaScript program to test whether an array of length 2 does not contain 1 or 3.
Exercise 11: Write a JavaScript program to display the current day and time in the following format.
Today is: Tuesday. Current time is: 10 PM : 30 : 38
Exercise 12: Write a JavaScript program to find the longest string from a given array of strings.
Exercise 13: Write a function that calculates the area of a circle given its radius.
Exercise 14: Write a JavaScript function that accepts two arguments, a string and a letter and the function will
count the number of occurrences of the specified letter within the string.
Exercise 15: Write a JavaScript program that creates a class (constructor function) called 'Vehicle' with properties
for make, model, and year.
▪ Include a method to display vehicle details.
▪ Create a subclass called 'Car' that inherits from the 'Vehicle' class and includes an additional property for
the number of doors.
▪ Override the display method to include the number of doors.
Exercise 16: Write a JavaScript program that creates a class called 'Employee' with properties for name and
salary. Include a method to calculate annual salary.
▪ Create a subclass called 'Manager' that inherits from the 'Employee' class and adds an additional property
for department.
▪ Override the annual salary calculation method to include bonuses for managers.
▪ Create two instances of the 'Manager' class and calculate their annual salary.
Exercise 17: Write a JavaScript function that changes the background colour of a div element when the user
clicks on a button in the same HTML web page.
Exercise 18: Write a JavaScript program to create a slideshow that changes the displayed image when a next or
previous button is clicked.
Exercise 19: Lets the code HTML below.
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Exercise-19</title>
<script type="text/javascript">
function couleur(parametre_couleur){
document.getElementById('dv').style.backgroundColor=parametre_couleur;
}
</script>
</head>
<body style="background-color:#FEF9E7">
<button onclick='couleur("blue")'> bleu </button>
<button onclick='couleur("green")'> vert </button>
<button onclick='couleur("red")'> rouge </button><br><br>
<div id='dv' style='height:500px;width:500px;background-color:black'></div><br>
</body></html>
23 | P a g e
CHAPTER 3: CLIENT-SIDE SCRIPTING LANGUAGES
4) Change the event from “onclick” to “onmouseover” and rerun the code in order to see the results.
Exercise 20: Create the HTML form presented in the figure below, then use a CSS file to format it by using the
following properties.
▪ The body element has a font size of 10 points, a font family in {Verdana, Helvetica, sans-serif} and a
very dark lime green colour for the text (#003300).
▪ The header element (h1) has a font size of 10 points and it is centred.
▪ The paragraph has the following margins 0, 40, 20 and 40 pixels
▪ The td element padding is 5 pixels.
▪ The td elements of the labels are right aligned, while td elements for the form elements are left aligned
Create a JavaScript program that will be used to verify that the user has entered all of the required data and that
the data is valid. Your form validation script should verify the following:
▪ the e-mail has the '@' symbol,
▪ at least one period exists after the '@' symbol,
▪ the user has entered a valid month between 1 and 12 inclusive,
▪ the day does not exceed the allowable value for any month (Be sure to account for 29 days in February
on a leap year (use the LeapYear () function.),
▪ the user has entered a year between 1800 and 2999,
▪ the user has entered text for the city,
▪ the user has selected a state, i.e., not left the default blank,
▪ zip code is integer from 0 to 99999 (don't worry about 9-digit zip codes or ensuring that there are
exactly 5 digits),
Note: For each error, please use an alert () function to tell the user how to properly enter the incorrect value.
24 | P a g e