A Study On Basic Javascript Programming Computer Science Essay

Published: Last Edited:

This essay has been submitted by a student. This is not an example of the work written by our professional essay writers.

We have see how HTML and XHTML are used to create the structure of web documents. We have also seen how CSS is used to control text properties as well as the properties of block elements such as borders, margins, padding and backgrounds. In this topic, we will look at a very exiting aspect of web design: client-side programming. Using a client-side programming language, we can create a large variety of effects and carry out many automated tasks in our webpage. The most popular client-side programming language is Javascript. Not only is Javascript used to create dynamic effects such us roll-over buttons, it is also used to validate HTML forms, create slideshows and, together with XML (to be dealt with later), is used to build web pages dynamically using AJAX (Asynchronous Javascript and XML). By applying the principles we learned in AICM652, you will learn the basics of programming with Javascript and be sufficiently prepared to start using advanced features such as the popular JQuery Javascript library.

Learning Outcomes

On successful completion of this topic the students will be able to:

Knowledge and Understanding

How a scripting language works, interpreters

History of Javascript

Uses of Javascript

Describe how Javascript programs are inserted in a web page

List Javascript versions and compatibility issues

Describe the Document Object Model for Javascript

Outline basic Javascript syntax and semantics

Describe the structure and operation of Javascript functions

Explain how event-based programming works

Explain the structure and operation of event-handlers


Insert Javascript into a web page using various approaches including inline code, internal scripts and external Javascript files

Write and use Javascript functions

Write simple Javscript event handlers to respond to different events on common web page objects such as images and hyperlinks

Create button roll-over effects

Implement form validation including use of regular expressions

Write a simple slideshow script


Acquire confidence in use of Javascript in a web page.

Key Terms


Syntax refers to the set of rules governing how a computer program is constructed using the keywords of that language.


With respect to computer programming languages, semantics refers to the meaning of language expressions. Special semantic notation is used to represent the semantics of a programming language.

Compiler and Interpreter

Compilers and interpreters are computer programs that convert computer programs written in high level languages such as Java into machine code or into an intermediate format suitable for execution by a microprocessor or a virtual machine. A compiler is different from an interpreter in that compilation is a batch process that converts an entire program at once while an interpreter converts and executes a statement at a time.

Document Object Model (DOM)

DOM is a way to represent the structure of an HTML document in a way that allows you to access and manipulate individual elements in a web page.


A function is a group of statements in a computer program that together perform a well-defined task. As an example, spreadsheets allow functions such as sqrt() to compute a square root and average() to compute the mean.

Form Validation

Form validation is the process of verifying that the information you enter into an HTML form meets some preset conditions. For example, only numbers may be permitted in a field requesting your phone number, therefore, we can check that only numbers are entered and no other characters.

ECMA-262 Standard

ECMA-262 is the formal standard that describes what is commonly known as Javascript. ECMA is the European Computer Manufacturers Association.

Introduction to Javascript

Javascript shares a lot of syntax with Java which you learned in AICM652. Therefore, a lot of Javascript syntax will be familiar to you. Javascript is an interpreted language that was designed for use on web pages from the beginning. Most modern browsers have in-built interpreters for Javascript. Jscript is the Microsoft version of Javascript. The only other well-known client-side programming language was VBscript which was based on Microsoft's Visual Basic syntax but is virtually extinct and is supported only by the Microsoft Internet Explorer. Part of Javascript's strength is the level of browser support. Because most modern browsers including the Internet Explorer, Firefox, Safari and Chrome support the ECMAscript standard, web programmers have confidence that their code will work no matter what browser the user is using.

Javascript is not a subset of the Java language but an entirely different full-featured programming language. It was developed by Netscape Communications in 1996 with the aim of allowing programming code to be embedded in a web page and be executed by web browsers. In 1997 the European Computer Manufacturers Association (ECMA) created a standard for Javascript officially called ECMAScript-262 which is currently at version 5 released in December 2009. The standard can be accessed at: http://www.ecma-international.org/publications/standards/Ecma-262.htm

Although Javascript has traditionally been viewed as a web-based programming language, it is increasingly being used outside browsers in applications such as GNOMEShell (http://live.gnome.org/GnomeShell). Several other applications outside the browser are listed at http://funkatron.soup.io/

More and more server-based implementations of Javascript have appeared. The first such server-side Javascript implementation was in the Netscape web servers which included a built-in extended Javascript interpreter.

Javascript impalements object oriented features using an object model that is different from the Java class-based object model. Inheritance is supported and includes properties and methods.

Uses of Javascript

Javascript is commonly used for form validation. Validation involves checking the user's input into an HTML form to verify that the data entered meets some set requirements. Validation is crucial in securing your web applications against hacker attacks and protecting against invalid data that may corrupt or crash your databases

Javscript is also used to implement dynamic effects such as roll-over buttons, conditional content and context-sensitive help. Conditional content is content that is formatted to suit a specific browser. Browsers have different behaviours and capabilities making it useful and sometimes necessary to create different versions of web pages for different browsers. Javascript allows the detection of browser type and subsequently customizes the webpage to suit the browser.

Javscript is also commonly used to add dynamic messages to a browser's status line, to create cookies, display messages to users, dynamically modify the current document, create dynamic images such as roll-over buttons, detect and react to events(such as mouse clicks), and to detect plugins and provide the user with information about these plugins. Plugins are software tools usually used to view special types of content such as PDF documents or Adobe Flash movies. A missing plugin will prevent the user from viewing such content.

More and more, Javascript is being used to implement some very sophisticated web-based applications. Excellent examples are GoogleDocs which include a web-based word processor drawing tools and spreadsheet (see http://googledocs.blogspot.com/2010/06/invite-someone-to-try-google-docs.html).

How a Scripting Language Works

Although Javascript is known as a scripting language and hence appears at first sight to have limited capability, it is a full-featured programming language. As we have seen above, the language is finding applications outside the browser.

However, it is also important to obtain a grasp of how a web scripting language works. A scripting language is interpreted meaning that the source code is executed statement by statement and the object code is not stored after interpretation. Javascript is more popularly known as a client-side (browser-based) scripting language but is also increasingly being used as a server-side language. The more popular server-side languages include PHP, PERL, Python and Ruby.

The source code in a Javascript web application is downloaded with the HTML then executed when required. As Javascript applications get more and more complex, there has been efforts to speed up the interpreters for better user experience. Compiled languages in general tend to perform better than interpreted languages because the conversion to object code (machine code) is done before execution. In scripting languages, conversion and execution and done in real time.

machine code:


Source code:

function Test()


document.write("Hello world")



Javascript Syntax

Variables and Identifiers

As you learned in AICM652, a variable is labelled container for data or objects. In Java the containers are "typed" meaning they can hold only the type of data they were created to contain. Javascript variables are not types meaning a variable can contain any data type.

You also learned that there are rules for naming variables that also apply for other types of program components such as classes, interfaces, and methods. In Javscript, the same naming rules apply. Names are called identifiers. Identifiers must start with a letter but can have both letters and numbers thereafter but no other symbols except an underscore (_). They can also start with an underscore. No spaces are allowed in an identifier.


Which of the following are invalid identifiers in Javascript. Explain why they are invalid?





First Name






Variables are declared and initialized with the var statement:

var j = 2+3+4; var x = 3, greeting = 'hello world';

Variable Scope: Scope refers to the location in your program where a variable may be used. This applies to arrays as well. There are two kinds of scope:

Local scope: A variable declared in a function has local scope and is visible within that function only. It can not be accessed outside that function hence can not be used outside that specific function in which it is defined.

Global scope: A variable declared outside a function is visible throughout the program. Such a variable is called a global variable However, it may be temporary invisible if you have used the same variable name inside a function in your program. Avoid using the same variable name more than once in your program. Variable names may also conflict across difference Javascript programs within a webpage if they use the same global variable name. To prevent this conflict, always declare variables with a "var" in from of the variable names as show in the example above.


Literals are real values rather than labels that represent values. Examples of literals include:



"In the beginning was the Word"

'Turn left'



Although Javscript variables do not have explicit data types, there are implicit types that include:

Numbers (both integers and reals)

Strings (enclosed by single or double quotes)

Boolean (true or false)

Null (meaning empty)

Each Javascript variable has an implicit data type that the interpreter recognizes but you not not have any explicit way to declare this type except by the types of values that are stored in a variables. When we study arrays, we shall find that, unlike arrays in Java that are typed, Javascript arrays can hold mixed data types. You can have strings and numbers in the same array.

As in Java, there are special characters that can be used as literals as follows:

\b represents a backspace.

\f represents a form feed.

\n represents a new line character.

\r represents a carriage return.

\t represents a tab character.

These can be used inside a quieted string as follows:

var message = "<html>\r"

Expressions & Operators

An expression is a combination of variables constants and operators written according to the syntax of the programming language you are using. Every expression evaluates to a value. This means that every expression works out to some value that that can be assigned to a variable. Some examples of Javascript expressions are shown below.

Algebraic Expression

Javascript Equivalent

y( n - m)


(m + n) (x + y)

(m + n) * (x + y)

(ab / c)

a * b / c

3x2 +2x + 1


(x / y) + c

x / y + c

In the same way that operator precedence applied in Java, Javascript expressions use the rules of operator precedence to evaluate expressions. The rules of precedence are given below with examples below showing how precedence affects the outcome of an expression. Always check that your expressions are correctly written taking precedence into account otherwise you will get logical errors that are difficult to trace. In some cases the errors may not be detected at all. The operators listed at the top of the table will be evaluated first and the ones at the bottom evaluated last.



. [] ()

Field access, array indexing, function calls, and expression grouping

++ -- - !

Unary operators

* / %

Multiplication, division, modulo division

+ - +

Addition, subtraction, string concatenation

< <= > >=

Less than, less than or equal, greater than, greater than or equal,

== != === !==

Equality, inequality, strict equality, and strict inequality


Logical AND


Logical OR



Work out the following examples following the rules of precedence. The correct answers are given to help you check your answers.

k = 100 * (96 + 4 + 50) Answer: k=15,000 Work out the brackets then multiply by 100

m= 2/3+20-10*5 Answer: m=10.6667 Start with division, then multiply then add and subtract.

If there are more than one operator at the same precedence level, in general you start evaluating from left to right. In the example above, division and multiplication are at the same precedence level, hence you carry out the division which occurs before the multiplication when starting from left to right in the expression.

Control Structures

Control structures in Java and in Javascript are identical. As a reminder these are listed below with a few examples of their use.

Decision/Selection structures

There are two basic decision structures in Javascript but there is also the ternary operator ":?". The two decision operators are the "if" statement and the "switch" statements. Below are examples of their use.

if (a >b)


//Do something


if (a >b)


//Do something




//Do something else


if (a =>70 && a<=100)


grade= "A"


else if (a =>60 && a<70)


grade= "B"


else if(....

Note that Javascript statements do not require a semicolon to terminate unlike in Java.

Switch Statement

switch (m)


case 1:

execute code block 1 if m=1


case 2:

execute code block 2 if m=2



// code to be executed if m is neither 1 nor 2


Repetition (Loops) structures







Javascript in HTML

Event-based programming

Basic HTML events

Document Object Model

Manipulating objects

Programming style

Javascript libraries

Using Javascript

Roll-over buttons

Form Validation


Introduction to Advanced Techniques (Ajax, scripting Java Applets etc.???)


Javascript Syntax Basics

Variables & Identifiers

Use the knowledge gained in AICM652 to avoid repetition. Point out only the differences.

Variables store single or multiple pieces of data

Physically, a variable is memory location in your computer

Arrays are variables that store multiple pieces of data under a single name

Identifiers are names

Names are used in variables, functions, objects, methods and properties

You do not need to specify data type for variables in Javascript (unlike C, C++, C#,Java…) have no type

Javascript however, has implicit types (type assigned by the interpreter)

Identifiers in Javascript

When naming functions and variables the name of the variable:

Must start with a letter or an underscore character ( _ )

After the first character, can contain letters, digits, and underscores

Cannot contain space

Declaring Variables

Variables are declared and initialized with the var statement:

var i = 1+2+3; var x = 3, message = 'hello world';

Variable Scope

Scope refers to where a variable is visible within a script -in other words, where it is accessible.

This applies to arrays as well. There are two kinds of scope:

Local scope: A variable declared in a function has local scope and is visible within that function only.

Global scope: A variable declared outside a function has global scope and is visible throughout the entire file, both within and outside of functions.

Variable Data Types

JavaScript supports three primitive data types:


booleans, and strings;

and two compound data types:

objects and arrays.

In addition, it defines specialized types of objects that represent functions, regular expressions, and dates.

Literals: Numbers

Numbers are represented in 64-bit floating-point format.

JavaScript makes no distinction between integers and floating-point numbers.

Numeric literals appear in JavaScript programs using the usual syntax:

a sequence of digits, with an optional decimal point and an optional exponent.

For example:





Integers may also appear in hexadecimal notation. A hexadecimal literal begins with 0x:

0xFF // The number 255 in hexadecimal

Literals: Booleans

The boolean type has two possible values, represented by the JavaScript keywords true and false.

These values represent

truth or falsehood,

on or off,

yes or no, or anything else that can be represented with one bit of information.

Literals: Strings

A JavaScript string is a sequence of arbitrary letters, digits, and other characters from the 16-bit Unicode character set.

String literals appear in JavaScript programs between single or double quotes.

One style of quotes may be nested within the other:




"Wouldn't you prefer O'Reilly's book?"

Literals: Escapes

When the backslash character (\) appears within a string literal, it changes, or escapes, the meaning of the character that follows it.

The following table lists these special escape sequences:

\0 The NUL character (\u0000)

\t Tab (\u0009)

\n Newline (\u000A)

\v Vertical tab (\u000B)

\f Form feed (\u000C)

\r Carriage return (\u000D)

\xnn The Latin character specified by the hexadecimal number nn; for example, \x0A is the same as \n

\uxxxx The Unicode character specified by the hexadecimal number xxxx; for example, \u0009 is the same as \t

Expressions & Operators

Arithmetic Operators

Relational Operators

Logical Operators

The logical operators perform operations on the logical values true and false.

The simplest logical operator is the NOT operator, represented by the symbol !.

It simply reverses the value of its operand, from true to false or vice versa.

The other logical operators combine two individual logical expressions to form a single logical value. They are:

AND (&&) returns true if both of its operands are true, and returns false otherwise (if one or both operands are false).

OR (||) returns true if either one or both of its operands are true, and returns false otherwise (if both operands are false).

Logical Operators (cont'd)

Logical Operators Examples (cont'd)

var x = true;

var y = !x;          //y has the value false.

var x = true;

var y = false;

var z = true;

var a;

a = x || y;            // a is true.

a = x && y;            // a is false.

a = y || !z;          // a is false

(note the NOT operator.

Assignment Operators

Other Operators

Bitwise Operators

Equality Operators

[Equality (==) and Identity (===)

Conditional Operator

x > 0 ? x*y : -x*y

Object Creation [new]

c = new Rectangle(3.0, 4.0, 1.5, 2.75); // Creates an object of class Rectangle

new constructor(arguments)

Control Structures

Decision or Selection

Repetition or Loop


if (condition)


//Statement block 1.




//Statement block 2.


The else statement and its following block of code are optional. If you have only single statements to execute you can omit the curly braces and use this syntax:

if (condition)



    Statement 2;

Selection cont'd

if (condition)


//Statement block 1.


else if (condition2)


//Statement block 2.


else if (condition3)


//Statement block 3.




//More statements.



for (var x = 0; x < 20; x++)


is equivalent to this:

for (var x = 0; x < 20; x++)




Brackets are optional for single-line statement

Repetition cont'd

while (condition)








while (condition)


Introduction to Functions

A function definition consists of the following:

The function keyword.

The function name, following the rules for Javascript identifiers that were described earlier in this tutorial.

A pair of parentheses ( ) that can optionally contain a list of one or more function parameters.

An opening curly brace ({).

One or more lines of Javascript code that constitute the function body.

A closing curly brace (}).

Functions (cont'd)

Consist of code in <script> elements that can be called by event handlers

Usually placed in <head> section


<Script type = "text/javascript">

function showAddress()


document.write("12404 Lockwood Drive #D4");



Function Call:

<a href="#" onClick = " showAddress()" > Address</a>

Function Example



<script type="text/javascript">

<!-- Beginning of JavaScript -

function changecolor(code)




// - End of JavaScript - -->





<input type="button" name="Button1" value="RED" onclick="changecolor('red');">

<input type="button" name="Button2" value="GREEN" onclick="changecolor('green;;')">

<input type="button" name="Button3" value="BLUE" onclick="changecolor('blue');">

<input type="button" name="Button4" value="WHITE" onclick="changecolor('white');">




In Head Section


<script type="text/javascript">

<!-- Beginning of JavaScript -

function changecolor(code)




// - End of JavaScript - -->



In Body Section



<input type="button" name="Button1" value="RED" onclick="changecolor('red');">

<input type="button" name="Button2" value="GREEN" onclick="changecolor('green;;')">

<input type="button" name="Button3" value="BLUE" onclick="changecolor('blue');">

<input type="button" name="Button4" value="WHITE" onclick="changecolor('white');">




See detailed introduction to functions in Javascript

Events and Event Handlers


Actions of the user such as clicking a mouse, moving into and out of a text box, pressing a keyboard key

Some actions are not directly caused by user such as loading a page

Events are associated with XHTML or HTML elements

No every element supports the same set of events

Event Handlers are scripts that respond to events

Events handlers are included within HTML/XHTML tags; not in <script> tags

Event Handlers

Event handler code executes when the event happens, such as pressing a button, moving your mouse over a link, submitting a form etc.

The basic syntax of these event handlers is:

Handler_name ="JavaScript code here"

Event Handlers (cont'd)

Example of an event handler:

<a href="http://google.com" onClick= "alert('Go Google!')" > Google </a>

Event is "onClick"

All Javascript event names start with "on"

Actual event is the click of the mouse button

The handler code is "alert('Go Google!')"

Event Handlers (cont'd)

Event handlers are most often implemented by calling Javascript procedures which are very similar to C procedures

Procedures are usually inserted in <script> elements in the head section of a web page

An example of such an event handler is shown in the following slide:

Events and Event handlers (cont'd)

So, what are event handlers? Very powerful and useful! They are JavaScript code that are not added inside the <script> tags, but rather, inside the html tags, that execute JavaScript when something happens, such as pressing a button, moving your mouse over a link, submitting a form etc. The basic syntax of these event handlers is:

name_of_handler="JavaScript code here"

For example:

<a href="http://google.com" onClick="alert('hello!')">Google</a>

Common Events Handlers

Problems With Events

Some bad news: All browsers do not handle all the same events.

Some events are browser-specific meaning they do not occur in other broswers

See event compatibility tables: http://www.quirksmode.org/js/events_compinfo.html

Use events that are implemented in all common browsers (not just the latest versions but even two/three generations back)


Introduction to Arrays

An array is a data type that contains or stores numbered values.

Each numbered value is called an element of the array, and the number assigned to an element is called its index.

Because JavaScript is an untyped language, an element of an array may be of any type, and different elements of the same array may be of different types.

Array elements may even contain other arrays, which allows you to create data structures that are arrays of arrays.

Creating Arrays

The first way is to call it with no arguments:

var a = new Array( );

The second method allows you to explicitly specify values for the first n elements of an array:

var a = new Array(5, 4, 3, 2, 1, "testing, testing");

The third way to invoke the Array( ) constructor is to call it with a single numeric argument, which specifies a length:

var a = new Array(10);

Note: These three methods are creating an object using "new" operator and "array()" constructor

Creating Arrays cont'd

Array literals provide a way to create arrays.

An array literal allows us to embed an array value directly into a JavaScript program in the same way that we define a string literal by placing the string text between quotation marks.

To create an array literal, simply place a comma-separated list of values between square brackets.

For example:

var primes = [2, 3, 5, 7, 11];

var a = ['a', true, 4.78];

Array literals can contain object literals or other array literals:

var b = [[1,{x:1, y:2}], [2, {x:3, y:4}]];

Accessing and Changing Array Contents

value = a[0];

a[1] = 3.14;

i = 2;

a[i] = 3;

a[i + 1] = "hello";

a[a[i]] = a[0];

if (a[i] < a[i-1])





Array Length

Used to determine array length:

var a = new Array( ); // a.length == 0 (no elements defined)

a = new Array(10); // a.length == 10 (empty elements 0-9 defined)

a = new Array(1,2,3); // a.length == 3 (elements 0-2 defined)

a = [4, 5]; // a.length == 2 (elements 0 and 1 defined)

a[5] = -1; // a.length == 6 (elements 0, 1, and 5 defined)

a[49] = 0; // a.length == 50 (elements 0, 1, 5, and 49 defined)

Document Object Model

Introduction to DOM


The Document Object Model (DOM) is an application programming interface (API) for valid HTML and well-formed XML documents.

It defines the logical structure of documents and the way a document is accessed and manipulated.

Introduction to DOM (cont'd)

In the DOM specification, the term "document" is used in the broad sense

XML is being used as a way of representing many different kinds of information that may be stored in diverse systems

Many "documents" would traditionally be seen as data rather than as documents.

Accessing Images

Accessing Images (cont'd)

By using name attribute:

<img name="myimage01" src="whatever.gif" />

Now, to access this image, this is what you'd do instead:

document.images["myimage01"] //first image


document.images.myimage01 //first image

Advanced Techniques (incomplete)

Web sites:





http://www.javascriptkit.com/domref/ DOM






Learning Activities

Exercise 1

Exercise 2

Exercise 3

Exercise 4.

Exercise 5

Summary of Topic



Please find the review Quiz 4 online at http://learn.egerton.ac.ke

Further Reading Materials


Harvey M. Deitel and Paul J. Deitel (2007). Internet & World Wide Web: How to Program (4th Edition). Prentice Hall( ISBN-10: 0131752421, ISBN-13: 978-0131752429)

Web-Based HTML Tutorials




Free Web Design E-Books

Web Design: http://yensdesign.com/2009/01/four-free-ebooks-web-developers/

Web Style Guide: http://www.webstyleguide.com