JavaScript

JavaScript is the programming language of the web. It is the language that underpins dynamic content on web pages. JavaScript runs in a JavaScript virtual machine. It is highly likely that you already have a JavaScript virtual machine installed on your computer; as long as you have a reasonably new web browser you have everything you need.

A little bit of history

JavaScript was first released in 1995 by Netscape Communications corporation as a lightweight client and server side programming language for the web. Although the language shares a similar name with a different programming language, Java, there is no relation between the languages. In 1996 JavaScript was submitted to an international standards body to become certified. The new standardised JavaScript was released under the name ECMAScript, however, it is still commonly named JavaScript.

Introduction to JavaScript

JavaScript is a client side web programming language, that is, the code runs in the browser rather than on the web server. JavaScript is used to modify the structure of a webpage. A webpage is a hyper text markup language (HTML) document. A HTML document is a structured document containing elements, the elements have attributes. When a web browser loads a webpage it retrieves the HTML document from the server and creates a document object model (DOM) from it before rendering the page for the user to interact with. JavaScript modifies the webpage by modifying the DOM, when a modification is made to the DOM the webpage is rendered again and the user is presented with the modified webpage.

Elements of a HTML document can have an id attribute, if an element has an id attribute then it is a unique identifying label for that element. The id attributes make it possible to target which part of the web page the JavaScript will change. For example to get an element from an id we can use the following line. In the snippet above the id attribute of the element that will be affected is example. The innerHTML attribute is set to "Hello world!!!".

It is also possible to change the styling of a webpage using cascading style sheets. Similarly to the previous example to modify the styling of an element first you must get the element then you can change the attributes of that element. To change the styling of an element using JavaScript you must modify the style attribute of the element. The following example changes the font colour of the element with id 'example'. The JavaScript language is as powerful as any other programming language. JavaScript has most of the same language features as any other imperative programming language, it has variables , for , while , if/else and functions.

JavaScript syntax

As with any other programming language JavaScript programs are a sequence of instructions that get run one after another in the same order as they appear. However, JavaScript differs from some programming languages in a number of ways. JavaScript is not white space dependent, that is white space nor indentation will alter the meaning of a JavaScript program. Instead JavaScript uses curly braces { } to denote a block of code. Although you have not seen any JavaScript yet the following snippet provides a view of how JavaScript compares to Python with respect to defining code blocks.

JavaScript

function add(a, b) {
  return a + b;
} 

Python

def add(a,b):
     return a  + b

Although indentation does not have any meaning in JavaScript it is still a good idea as it help make the code readable. Another important difference between JavaScript and Python is that in JavaScript every line containing an instruction has to be terminal by a semicolon ( ; ).

JavaScript keywords

JavaScript has a set of keywords, these keywords are reserved and can not be used as function or variable names. The table below lists the keywords in JavaScript.

abstract arguments boolean break byte
case catch char class* const
continue debugger default delete do
double else enum* eval export*
extends* false final finally float
for function goto if implements
import* in instanceof int interface
let long native new null
package private protected public return
short static super* switch synchronized
this throw throws transient true
try typeof var void volatile
while with yield

Where to put JavaScript

JavaScript can either be written in the HTML file or in a separate file which is then included in the HTML document, using a script element. JavaScript can be placed in either the body or head tag in a HTML document. To include JavaScript in a HTML document the HTML script tag is used, the following snippet demonstrations how to include JavaScript directly into a HTML document.

<script>
<<JavaScript code>>
</script>

Any JavaScript code can be placed in the script element and you can have several script elements in a HTML document.

An alternative to typing JavaScript into a HTML document it is possible to save the JavaScript in a separate file. Files that contain JavaScript code have the file extension '.js'. This approach has several advantages including promoting reuse of code and separating the logic and presentation of an application. To include JavaScript in a HTML document stored in a separate file the script element is used again, but this time we set the src attribute to the uniformed resource locator (URL) of the JavaScript file.

<script src="script.js"></script>

You can include external JavaScript file anywhere in the head or body elements of a HTML document.

JavaScript basics

JavaScript has a number of different way of displaying it's output. JavaScript can display it's output using any of the following;

  • document.write() - will write to the document. If the document has been loaded then writing to the document will erase the document.
  • innerHTML - will set the innerHTML property of a HTML element.
  • window.alert() - will create a popup box and display a supplied message.
  • console.log() - will display a message in the JavaScript console. The console is visible in the browser debugging view.

Next we show examples of how to use each of the methods listed above.

document.write()

This method will print into the document stream as it is being processed by the browser. If the document has be completely loaded and this method of output is used then it will erase the entire document, therefore this method is unsuitable for use in event handlers (something that will be covered later).

<script>
document.write("Hello world!!!");
</script>

Try it yourself

innerHTML

This method changes the HTML content of an element. To use this method first you must get the HTML element.

<script>
document.getElementById("example").innerHTML = "Hello world!!!";
</script>

Try it yourself

window.alert()

This method of displaying an output will create a popup notification window.

<script>
window.alert("Hello world!!!");
</script>

Try it yourself

console.log()

All modern browsers have a console where information about the page is output. This method of displaying an output writes to this console. This method is not suitable for displaying a result to users as a 'normal' user will not be familiar with the JavaScript console log. This method is favoured during development as it allows the developer to view information without changing the asthetics of the page.

<script>
console.log("Hello world!!!");
</script>

Try it yourself

In different browsers there are different ways of accessing the browser console;

  • Chrome
    • Mac - Command + Option + J
    • Windows - Ctrl + Shift + J
    • Linux - Ctrl + Shift + J
  • Internet Explorer - F12
  • Firefox
    • Mac - Command + Option + J
    • Windows - Ctrl + Shift + J
    • Linux - Ctrl + Shift + J

Variable

In JavaScript you must define a variable as being a variable before it is used (although there is a concept of hoisting variable), this is done using the var keyword. As in most other programming languages the = symbol is the assignment operator.

var x = 5;
var y = "this is a string";
var z = [];

The code above will create three variable x , y and z . The values of the variables are 5, "this is a string" and [] respectively. If you define a variable but do not assign it an initial value then the variable will have the value undefined .

Data types

JavaScript defines 7 data types; six of them are primitives and the final one is objects. Data types are used for storing different types of data in a computer. The data types in JavaScript are;

  1. Null - represents something that does not exist (ironically the Null is an object, and diffinitely does exist)
  2. Undefined - is the value a variable gets when it is defined by but assigned a value
  3. Boolean - represents a boolean value (True/False)
  4. Number - JavaScript only have one number type, it can represent decimals and non decimal numbers
  5. String - represents a sequence of characters
  6. Symbol - represents a unique and immutable identifier (new feature which is not widely supported)
  7. Object - represents an object (in the object oriented programming sense). Although we will use object we will not cover them in depth in this module.

The following sample demonstrates how to initialise a variable with each of the data types listed above (except Symbol and object).

//  create a variable called 'a' and assign it the value null
var a = null;

// create a variable called 'b' of undefined type
var b;

// create a varibale 'c' and assign it a boolean value
var c = false;

// create a variable 'd' and assign it a number with a decimal point
var d = 42.5;

// create a variable 'd' and assign it the value of 42
var d = 42;

// create a variable 'e' and assign it a string value
var e = "Hello world!!!";

Operations

The arithmetric operations use the same notation as in most programming languages, in fact the notation for the arithmetric operations are consistent across many programming languages.

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
var x = 5;
var y = 4;

//Addition of y and x, the value is stored in variable z
var z = y + x;

//Subtraction of y from x, the value is stored in variable z
var z = y - x;

//Multiplication of y and x, the value is stored in variable z
var z = y * x;

//Division of y by x, the value is stored in variable z
var z = y / x;

There are a number of shorthand versions of some of the arithmetric operations. These shorthand versions compute the operation and perform the assignment. For example the following snippet adds x and y and stores the result in variable x .

var x = 4;
var y = 5;

// x will have the value 9 afte the instruction has been run
x += y;

There are similar operators for the other arithmetric operations. The table below summaries the common ones.

Operator  Usage Equivalent to
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y

For the string data type the + symbol has the same menaing as in Python, the + symbol concatenates two strings together.

var a = "Hello";
var b = " world!!";

// c has the value "Hello world!!" after this instruction has been run
c = a + b;

The last kind of operation we should consider are the comparison operations, these are the operations that result in a boolean value. The JavaScript comparison operations are very similar to those in any other programming language, however, JavaScript has a couple of additional operations.

Operator Description
== equal to
!= not equal
> greater than
< less than
>= greater than or equal to
<= less than or equal to
=== equal value and equal type
!== not equal value or not equal type

Scope

In programming in general scope is the set of variables and functions that are accessible from a given location in the code. In JavaScript there are two types of variables; local variables and global variables. A variable is local if it is defined within the body of a function. A local variable is not available after the function has been run. The other type of variable is the global variable, a variable is global if it is not local. The following snippet illustrates the idea of scope in JavaScript.

function centerPoint(a,b){
// sum is a local variable because it is defined within the body of a function
var sum = a + b;
return sum /2;
}

function max(a,b){
//x is a global variable
// although the variable is used in the function, it is not defined in the function
// because the var keyword is missing. This is a consequence of a feature JavaScript
// has called variable hoisting
x = a + b;
if(a >=b){
  return a;
} else {
  return b;
}
}

// x is a global variable
var x;

Repetition

Repetition in programming languages allow a section of code to be executes a number of times without having to copy and paste the code. Repetition is a standard feature of many programming languages. JavaScript hastwo types of repetition; while and for loops. They are often called loops because when the code is executes and it gets to the end of the section that should be repeated the execution loops to the top of the repeated section.

for loops

JavaScript supports a couple of variations of for loops. The general form of the for loop is;

for(<<initialiser>>;<<condition>>;<<afterthought>>){
<<code>>;
}

Where <<initialiser>> , <<condition>> and <<afterthought>> have the following meanings.

  • <<initialiser>> - is run before the for loop starts. Often this is where variables are initialised that are used in the loop.
  • <<condition>> - is the terminating condition, the for loop will continue to run until this expression evaluates to false.
  • <<afterthought>> - is run each time the body of the for loop is run. Often this is where variables used in the loop are updated before running the body of the loop again.

Lets look at how this type of for loop could be used to iterate through the elements of an array. In the following example the code will compute the arithemtic mean of the number in an array.

var numbers = [99, 45, 3, 8, 33, 58, 107, 41];
var sum = 0;
for(var i = 0; i < numbers.length;i++){
sum = sum + numbers[i];
}
var average = sum / numbers.length;

JavaScript also has another type of for loop. This type of for loop is ofetn refered to as foreach.

var numbers = [99, 45, 3, 8, 33, 58, 107, 41];
var sum = 0;
var x
for(x in numbers){
sum = sum + numbers[x];
}
var average = sum / numbers.length;
  1. Create a HTML document that uses JavaScript to display the first 10 numbers (starting from 0) using a for loop. You should use the innerHTML method of displaying the output.

  2. Create a HTML document that uses JavaScript to display the numbers 25 through to 13 using a for loop. You should use the innerHTML method of displaying the output.

  3. Create a HTML document that uses JavaScript to display the even numbers 25 through to 0 using a for loop. You should use the innerHTML method of displaying the output.

while loops

There are two types of while loops in JavaScript. The difference between the two types is minor. The general form of a while loop in JavaScript is

while(<<condition>>){
<<code>>;
}

while loops execute the body of the loop while the condition evaluates to true.

Let's look at an example of using while loops in JavaScript;

var x = 10;
var sum = 0;
while(x < 10){
sum = sum +x;
x = x +1;
}

The example sums the first 10 integers (including 0).

An alternative type of while loop that JavaScript has is called the do/while. The general form is;

do  {
<<code>>;
} while (<<condition>>);

This type of while loop differs slightly from the first type of while loop. This type of while loop will run the body of the loop once before testing the condition. The loop will continue to run while the condition is true. In summary the only different between the two types of while loop is that with the do/while loop the body of the loop is guaranteed to run at least once.

  1. Create a HTML document that uses JavaScript to display the first 10 numbers (starting from 0) using a while loop. You should use the innerHTML method of displaying the output.

  2. Create a HTML document that uses JavaScript to display the numbers 25 through to 13 using a while loop. You should use the innerHTML method of displaying the output.

  3. Create a HTML document that uses JavaScript to display the even numbers 25 through to 0 using a while loop. You should use the innerHTML method of displaying the output.

  4. Create a HTML document that uses JavaScript to display the numbers between 0 and 10 using a do/while loop. You should use the innerHTML method of displaying the output.

Conditional execution

Conditional execution is an important part of programming, it lets the programmer decide which parts of the program gets execute depending on some condition. JavaScript has a number of different types of condition statements. JavaScript has the following types of condition statements;

  • if
  • else
  • if/else
  • switch

The if statement works by testing the condition, if the condition evaluates to true then the section of code gets executed otherwise the section of code does not get executed. The general form for a if statment in JavaScript is;

if(<<condition>>){
<<code>>;
}

The body of the if statment will run if the condition evaluates to true. As with many other programming languages the if statment can also be coupled with an else statment that will run in the event that the condition evaluates to false. For example;

if(x > 10){
// run when x is greater than 10
} else {
// run when x is less than or equal to 10
}

The else if statement allowsthe programmer to specify a set of conditions. The setions of code are mutually exclusive, that is only one of the sections of code can be executed. The conditions are tested in the sequence they appear in the code,the first condition that is true is the section of code that gets executed.

if(x > 10){
// run when x is greater than 10
} else if(x > 3){
// run when x is less than or equal to 10 and greater than 3.
} else {

}

The last type of condition statment in JavaScript is the switch statement. It is possible to achieve the same functionality using else if statements. The switch statmenet allows for the selection of a block of code to be run based on the value of a variable. The general form of the switch statment is;

switch(<<expression>>){
case <<value_1>>:
  <<code_1>>
  break;
case <<value_2>>:
  <<code_2>>
  break;
case <<value_3>>:
  <<code_3>>
  break;
}

The switch statement is evaluated once, the value of <<expression>> is matched against each of the case statements. The code associated with each case will be run if it matches the value of the expression. In the example above if the break instsructions were not there then the switch statement would continue to match the expression against the cases. Because the break statments are there then the first case the epression matches will be run and then the switch statement will be exited.

Let us look at an example of how a switch statement might be used. The getDay method returns a number which indicates which day of the week it is, i.e. Sunday = 0, Monday = 1, Tuesday = 2 ...

switch (new Date().getDay()) {
  case 0:
      day = "Sunday";
      break;
  case 1:
      day = "Monday";
      break;
  case 2:
      day = "Tuesday";
      break;
  case 3:
      day = "Wednesday";
      break;
  case 4:
      day = "Thursday";
      break;
  case 5:
      day = "Friday";
      break;
  case 6:
      day = "Saturday";
      break;
}

When the switch statement has been run the variable day will contain a string containing the day of the week.

  1. Create a HTML document that uses JavaScript to display the string "too high" if the variable x is greater than 10 or "too low" if it is less than 5 or "just right" otherwise.

  2. Create a HTML document that uses JavaScript to display an appropriate greeting to the user based on the time of day. Your solution should display "Good Morning" or "Good afternoon" based on the time of the day. To get the time of day using JavaScript use the following snippet

    var date = new Date();
    // hours will contains a value between 0 and 23 corresponding to the time of day.
    var hours = date.getHours();
  3. Create a HTML document that uses JavaScript to display an appropriate greeting to the user based on the time of day. Your solution should use a switch statement and display "Good Morning", "Good afternoon" or "Good evening" based on the time of the day. To get the time of day using JavaScript use the following snippet

    var date = new Date();
    // hours will contains a value between 0 and 23 corresponding to the time of day.
    var hours = date.getHours();

Functions

Functions are a really important concept in any programming language. Functions takes some values (maybe none) and return some value. The purpose of a function is to prevent duplication of code and to increase the readability and to expose the purpose of a piece of code. A function is a section of code that has a name associated with it. This name allows the section of code to the executed whenever the programmer wishes simply by calling the function.

The definition of a function in JavaScript is similar to that in Python.

function <<functioName>>(<<arguments>>){
<<body>>;
}

A concrete example of how we might define a function in JavaScript is provided below, the function add computes the summation of two numbers. The keyword return works by passing the value back to wherever the function was called.

function add(a, b){
return a + b;
}

In JavaScript it is possible to assign a function to a variable, technically this is also possible in some other languages. In JavaScript this is a feature that is used extensively so we should mention it. To assign a function to a variable we use the following notaion;

var add = function (a, b){
return a + b;
};

The function defined in the above example is called an anonymous function as the function does not have a name. To call an anonymous function we use the normal notation.

add(4,5)
  1. Create a HTML document that uses JavaScript to display the number of day until the next weekend. Create a function that returns the number of days until the next weekend.

  2. Create a HTML document that uses JavaScript to display the day of the week. Create a function that returns the day of the week as a string. Hint: it would be a good idea to use a switch statement.

  3. Create a HTML document that uses JavaScript to display the distance in miles and kilometres. Create a function that returns the distance in milometres given a distance in miles. Use the function to display a message to the user.

  4. Create a HTML document that uses javascript to display the distance in miles and kilometres. Create a function that returns the distance in miles given a distance in kilometres. Use the function to display a message to the user.