1

Christopher Smith
Using Examples to Teach JavaScript via the World Wide Web
April 2008
Project Supervisor: Dr Jonathan Deane
Submitted as a report for the BSc Mathematics degree at the University of Surrey

Abstract:

The use of the internet has become vast over the last decade. People are now able to buy webspace and create their own webpages, so the ability to produce well presented interactive webpages is more important than ever.

JavaScript is an important language in the creation of webpages as it allows the creator to add interactivity. It can also be used to alter the style and look of a webpage as well as many other features.

This project is designed to teach JavaScript to a basic/intermediate level. I will teach by a combination of mini-examples to show the use of individual commands and by using larger examples, showing how these commands can be put together to create a useful program. The website will focus mainly on the more basic aspects of the language and allow users with no prior experience of JavaScript to be able to learn.

I found that there are definite advantages over learning from a textbook. A website is also updatable if new standards in the language are created. The use of quizzes with instant feedback really gives the user the chance to test themselves instantly and find out how much they truly know.

Each of the larger examples was created by myself to show how the various commands in JavaScript can be used. This shows technical achievement as each of the examples contains a different set of commands and how they can be used.

1

Contents:

Chapter 1) Introduction, Background and Motivation

  • Aims

Background:

  • History of JavaScript
  • What is JavaScript
  • What can JavaScript do
  • Official name

Motivation

Chapter 2) Process

  • Simple JavaScript examples

Worked Examples:

  • Three Doors
  • Calculator
  • Hangman
  • Cantor Tertiary Set
  • Pi Estimation
  • Integration
  • Style Changer
  • Quiz
  • Code Testing Page
  • Teaching Pages

Chapter 3) Conclusion

  • Critique
  • Learning
  • Improvements
  • Conclusion

4

4

5

6

6

6

8

9

11

14

17

21

27

29

30

31

32

38

39

39

40

1

Chapter 1) Introduction, Background and Motivation:

Aims:

  • Software to teach JavaScript, demonstrating technical achievement (i.e. not just typing).
  • Working by example.
  • Tests and quizzes with instant feedback.
  • To show advantages over learning from a textbook.
  • To aim teaching at beginner/intermediate level.

The internet is used more and more for teaching purposes. With the massive growth of accessibility to the internet in homes, at work or in schools the availability of good user friendly teaching websites is very important.

The purpose of this website is not only to be an online resource but to show how websites can be made interactive and user friendly using JavaScript.

Background:

History of JavaScript:

When the World Wide Web first became prominent in the early 90’s all web pages were static and provided no user interaction. To make webpages interactive a new computer language needed to be created. The two most popular web browsers at the time were Netscape and Internet Explorer. The first of these to bring out a programming language was Netscape. They called it Livescript, and this allowed anyone who used Netscape to view and use interactive webpages.

Livescript was integrated into the browser which meant that the browser interprets the code directly and does not need to compile it or use a plug-in for it to run.

Java was a programming language that was becoming more and more popular at the time.However Java required a separate plug-in for the code to run. Netscape decided to change the name of their programming language to JavaScript to cash in on this growing popularity.

Although similar in name, the languages of Java and JavaScript are entirely different.

Java is a language that will stand on its own whereas JavaScript requires an HTML document to run. Java is a much larger language and can be used to create applets that run independently. When used in web design java must be compiled before it is processed by the browser. The compiler turns the java code into a language that can be read by the browser. JavaScript is text based and is processed directly through the HTML browser. JavaScript code can be altered after the code has been processed whereas java code can’t be changed after it has been compiled. If a change needs to be made, the original code must be changed then re-compiled.

Internet Explorer decided to make its browser compatible with not one but two programming languages. The first was vbscript which was based on the BASIC programming language. The other was Jscript which shared many similarities with JavaScript.

Jscript is still used today but only by Internet explorer and any code that is programmed as JavaScript is taken by internet explorer and interpreted as Jscript. The biggest difference between the two languages now is the extra commands in Jscript that allow it to access activeX and the local computer. This is mainly used on intranet sites where internet explorer can be configured on each machine to allow these commands.

As Netscape was the most popular browser at the time, Internet Explorer altered Jscript to be more and more like JavaScript. It was even possible to write code that would run on both systems if you were very careful.

By the time Internet Explorer overtook Netscape as the most popular browser, JavaScript had been accepted as the standard for writing interactive code in webpages.

JavaScript was handed to Ecma International (originally “European Computer Manufacturers Association, EMCA”, now no longer considered an acronym or use of full capitalization) in 1996 so that an external body could be in charge of the development of the language. This meant that the language was no longer in the hands of competing developers and so an international standard could be created.

What is JavaScript:

  • JavaScript was originally created to add interactivity to web pages.
  • JavaScript can be imbedded into HTML code or in external .js files.
  • JavaScript is a scripted language (definition below) with individual lines of executable code.
  • JavaScript is an interpreted language which means the browser does not need to compile the code before it is run.
  • Anyone can use JavaScript and you don’t need a licence to use it.

A scripted language is one that is interpreted by another program at runtime rather than being compiled by the computer.

What can JavaScript do:

JavaScript can be used to serve many purposes within a website:

  • Anyone can use the code to add interactivity to their webpage.
  • JavaScript can be programmed to react to certain events such as clicking, scrolling, typing or simply moving the mouse over an object.
  • JavaScript can be used to put dynamic text into a webpage.
  • JavaScript can be used to change the style properties of a webpage.
  • JavaScript can be used to create cookies which store small pieces of information.
  • JavaScript can be used to detect the visitor’s browser and therefore change the following page to suit the browser.
  • JavaScript can be used to validate and send data to a server.

Official Name:

  • The real name of JavaScript is “ECMAScript” after the Ecma organisation who develop and maintain the language.
  • The official standard is called “ECMA-262”.
  • It has been included in every Internet Explorer and Netscape browser since 1996. It is now included in many other browsers including: Mozilla, Firefox and Opera.

Motivation:

While on my placement year during university at CACI, part of my job was to keep our part of the intranet site up to date. Knowing nothing about HTML, CSS and JavaScript before this time, I decided to teach myself these languages. There were plenty of examples of HTML, as the source code from each webpage can be viewed. This means that finding an example of code touse is easy. The problem I found was finding a simple teaching website for JavaScript that included useful examples to learn from. Many of them use mini-examples within the teaching pages but do not show a use of the code within a larger example.

To learn the language myself I used a combination of websites, books and trial and error to create my working examples.

With the growing availability of personal websites and web spaces, it is important for people to be able to access easy and user friendly ways of learning how to create interactive websites.

Many of these websites are difficult to use because of the mass of information on each page and the lack of useful examples to follow.

I will try to explain each element of using JavaScript carefully with use of mini-examples on each page and by use of larger examples that show many JavaScript functions working together.

I believe that using examples to teach is a lot more effective than just putting the individual elements of code on the screen for the end user to learn.

Learning from a book can be very difficult. There are no interactive examples, no way of testing your code instantly and it can be more difficult to find the exact reference you are looking for.

A book can also become out of date and to update it would mean printing more copies. For the end-user to keep up to date with the new code they would be required to buy a completely new book. The advantage of web based teaching pages is that they can constantly be updated to keep up with changes in the language and also expanded if the web developer feels that a particular area could be expanded further.

A book does have advantages over a website in some aspects. A book can be taken anywhere and read whenever you feel free to do so, whereas a website needs internet access which isn’t always available.

Chapter 2) Process:

My first task was to create a style for my website so the pages had a similar theme running throughout them. This meant keeping colours, fonts and sizes the same. To do this I used a CSS (Cascading Style Sheet). This is an external document that sits alongside the website and defines the styles used. Each tag can be defined with a different style as well as having unlimited classes for each tag type. This gives massive flexibility for web styling and stops the HTML code becoming too crowded. This was another language that I had to learn in order to start work on this website.

It was also important for me to expand my knowledge of HTML as this was the language I would be building my website with. I knew most of the basic tags and how they worked but it was important for me to know how these could be linked with JavaScript code to produce the results I wanted.

I then set about learning more of the JavaScript I would need to know inorder to produce the examples I needed and ultimately produce the teaching website. I found the easiest way to do this was to dive straight into creating the examples I would use in my website with help from books and online material.

Simple JavaScript Examples:

In this section I will show a few simple examples of JavaScript that show basic functionality and layout. There are several commands that I refer to frequently throughout this report, so I will provide examples here as reference to their functionality:

alert() function:

The alert() function produces a small popup box on the screen. It will display anything that is placed within the parentheses in the box. Variables placed within the parentheses will display their stored value and anything contained within quotes “ “ will be displayed as a string. The following code will produce the following popup:

alert(“Hello world!”);

for loop:

The for loop is a simple loop consisting of 3 parameters. The first of these specifies the variable you wish to count by, the second provides the clause by which the loop will continue iterating while it remains true and the third is the numberby which the count variable is increased each time the loop runs.

var count=0;

for(var i=0, i<=10, i++) count ++;

alert(count);

This will produce an alert box similar to the one above with the total for the count variable in. In thiscase, 11.

if and if-else statement:

The “if” statement produces a true of false value based on the outcome of a test. The test is contained within parentheses that follow the “if” statement. If the result is returned true then any commands that follow the parentheses are carried out.

if(test < 5) count++;

else count--;

This code tests to see whether the variable namedtest is less than 5. If it is then the code will add one to the value of count, if not the else statement will subtract one from the value of count.

Worked Examples:

Three Doors:

The Three Doors probability problem has been around for many years. The problem envisages three doors, one of which has a prize hidden behind. One player knows which door has the prize behind it.The other player chooses a door. They are then shown by the first player what is behind one of the remaining doors, but not the door with the prize. The second player is then given the option of changing their choiceto the other remaining door or sticking with the one they originally chose. All the doors are then revealed and the player sees if they have won.

New features:

  • creating functions
  • lines ending with ; (semicolon)
  • assigning variables
  • creating arrays
  • if and if-else statements
  • alert command
  • changing source links (src)
  • confirm command
  • random number generator
  • for loops
  • use of graphics

The features above are new features whose use is illustrated by this program. A brief explanation of their use is included below in the order they appear in the list.

A function is a reusable block of JavaScript code that can be executed by an event.

Each line in JavaScript must end with a “;” (semicolon). This tells the browser that it is at the end of a line of code when it is processed.

Variables are assigned using the var operator. Variablescan be in 3 formats; boolean, numeric or string:

  • assign a boolean variable: var a = true; or var a = false;
  • assign a numeric variable: var b = 12.65;
  • assign a string variable: var c =’’hello world’’;

An array is used to store a set of values using one variable name:

  • Set up an array: var a = new Array(4);
  • This creates the elements: a[0], a[1], a[2], a[3]
  • Each of these can contain a boolean, numeric or string variable.

The src property is used within the <img> tag in HTML to define a link to a picture. This picture is then displayed on the webpage. The src property stands for the source of the link. This property can be changed using JavaScript:

  • Define the HTML tag: <img src=”pic1.jpg” name=”picture”</img>
  • Change the link in JavaScript: document.picture.src=”pic2.jpg”;
  • This will change the image on the webpage from: pic1 to pic2

The confirm command produces an alert box with an “ok” and a “cancel” button. The two buttons return a true and a false value respectively.

The random number generator is a function that is built into JavaScript and produces a pseudo-random number between 0 and 1. It can be accessed by using the code:

  • Math.random()

Advanced features:

  • Random number generator
  • Nested “for” loops
  • Nested “if” statements

The page started out by having three buttons to represent the doors. I soon changed this by creating the doors as large blocks of colour, a different colour whether the door was closed, right or wrong when opened. By placing the link to the JavaScript function on the images of the doors, it allowed the user to click on their choice of door to select it.

The JavaScript code starts with a separate function for each door that is clicked. This set a choice variable to the relevant door and then passed this number onto the main function. The main function used a random number generator to assign the prize to a door and this is stored in an array. The program then opens a door with no prize behind it using another random number generator when there’s a choice.The image of this door then changes to an open door. A message is then displayed asking the user if they want to swap, and a flag is set depending on their answer. This flag passes through some “if” statements and the relevant action is taken whether to swap or not.

The program then checks the user’s chosen door against the right door that is stored in the array. The user is then informed by a message if they chose the right door. All the doors are then revealed to show the user where the door with the prize behind was.

To show how the probability changes as to whether you swap or not, I needed to create a function that would do the above process automatically many times over without any extra intervention from the user.