PALS3004/G308 Web Programming
SPEECH, HEARING & PHONETIC SCIENCES
UCL Division of Psychology and Language Sciences
PALS3004/G308 Web programming for research in psychology and language sciences

6. Javascript Language Part 2

Learning Objectives

By the end of the session you should:

Topics

  1. Conditional Statements
  2. If-Else

    The Javascript conditional statement allows you to control whether a block of code is executed depending on the value of some boolean expression. It has the basic form

    if ( expression ) {
      statements to be executed if expression is true
    }
    

    For example:

    if ((inpval < 1)||(inpval > 10)) {
      alert("Please enter a number between 1 and 10");
    }
    

    An "else" block can be added to allow a choice between two outcomes:

    if ( expression ) {
      statements to be executed if expression is true
    }
    else {
      statements to be executed if expression is false
    }
    

    The {} brackets can be dropped if there is only one statement.

    For example:

    if (n==1)
      alert("You have 1 new message");
    else
      alert("You have " + n + " new messages");
    

    A chain of conditional statements can be created with

    if  ( expression1 )
      statements to be executed if expression1 is true
    else if ( expression2 ) 
      statements to be executed if expression1 is false
        and expression2 is true
    else
      statements executed if both expressions are false
    

    For example:

    if ((age < 0) || (age > 120))
      console.log("illegal age value");
    else if (age < 18)
      console.log("young person");
    else if (age < 65)
      console.log("working age");
    else
      console.log("pensioner");
    

  3. Structured data
  4. Arrays

    Arrays are tables of variables where individual elements of the table can be accessed through an integer index. For example, the statement

    var tab = new Array(5);
    

    Declares a table of 5 variables, called: tab[0], tab[1], tab[2], tab[3] and tab[4]. The square brackets indicates that we are accessing elements of an array, and the number in the brackets must be a non-negative integer. The first element of an array has index zero.

    Javascript arrays automatically change size depending on which elements are in use. This means that you can declare an array as zero sized, and still assign values to elements using indices, for example:

    var tab=[];       // empty array
    tab[0]="hello";
    tab[1]=23.4;
    tab[2]=false;
    

    Also note in this example that array elements can hold any Javascript type, just like simple Javascript variables.

    You can also initialise an array in the declaration statement:

    var tab = [ "hello", 23.4, false ];
    

    Arrays maintain a property length which tells you the current number of items stored in the array (assuming no empty slots). In the example above tab.length would have the value 3.

    Note that if you assign an array to a new variable, the contents are not copied. Instead both variables end up referring to the same array. However you can make a true copy of part of an array using the slice() method, see below.

    var tab=[1, 2, 3, 4];
    var alttab=tab;         // SAME array with new name
    var newtab=tab.slice(); // COPY array into new variable
    
    Array Methods

    These array methods are available for use on all arrays.

    MethodExampleDescription
    concat(array)ary3=ary1.concat(ary2)Creates a new array which is the concatenation of the original array and the given array.
    slice(start,stop)ary2=ary1.slice(2,4)Returns a new array that is a copied section of the original array. Extraction starts at index start and ends just before index stop. If stop is missing, returns rest of array to end.
    join(separator)str=ary.join(";")Returns a String object consisting of all the elements of an array concatenated together with the given separator string.
    pop()val=ary.pop()Removes the last element from an array and returns it.
    push()ary.push(100)Appends new elements to an array, and returns the new length of the array.
    shift()val=ary.shift()Removes the first element from an array and returns it.
    unshift(val)ary.unshift(23)Inserts new elements at the start of an array.
    sort()ary.sort()Sorts the array object into alphabetical order.
    reverse()ary.reverse()Reverses the order of the elements in the array.

    Object Structures

    You can group named variables together into a structured data object. This allows you to manipulate groups of variables in single statements. For example, we might put together the co-ordinates and plotting character for a point on a graph:

    var point= { x:23, y:17, plotchar:"x" };
    

    We can then access/change the stored values within point using the dot notation: point.x, point.y, and point.plotchar:

    var xcoord=point.x;
    point.y=200;
    point.plotchar="*"; 
    

    You do not need to pre-define what properties are held on an object. We can create an empty object then add properties one by one, for example:

    var point={};     // empty object;
    point.x=23;
    point.y=17;
    point.plotchar="o";
    

    In some ways objects and arrays are similar, just that array elements are indexed using integer indices, while object properties are indexed by name.

    You can test to see if a property is defined on an object using the method "hasOwnProperty()", for example:

    if (!point.hasOwnProperty("plotchar")) 
      point.plotChar="x";
    

    You can delete a property using the special delete statement:

    delete point.plotchar; // "plotchar" property removed
    

    You can also create arrays of structured objects, or structured objects containing arrays, e.g.

    var ptable=new Array(5);
    ptable[0]={ x:1, y:10 };
    ptable[1]={ x:2, y:20 };
    ptable[2]={ x:3, y:30 };
    ptable[3]={ x:4, y:40 };
    ptable[4]={ x:5, y:50 };
    var npoint={ x:[1,2], y:[20,30], chars:[ "*", "o" ] };
    npoint.x[1]=10;      // changes existing value of 2
    npoint.chars[0]='O'; // changes existing value of "*"
    

    Note that if you assign an object to a new variable, the contents are not copied. Instead both variables end up referring to the same object. However you can copy across the properties of an object individually to a new object.

    var obj={ a:1, b:2, c:3 };
    var altobj = obj;    // new name for SAME object
    var newobj={};       // create new COPY of object
    newobj.a=obj.a;
    newobj.b=obj.b;
    newobj.c=obj.c;
    

  5. Looping Statements
  6. The while and for statements allow you to execute a block of statements repetitively. You use a while loop when you want to repeat something as long as some boolean expression is true. You use a for loop when you want to repeat something a known number of times.

    While loops

    The syntax of a while loop is

    while ( boolean-expression ) {
    	repeated statements
    }
    

    For example (find power of 2 bigger or equal to given number):

    function powerof2(n) {
       var p2=0;
       while (Math.pow(2,p2) < n) {
          p2 = p2 + 1;
       }
       return(p2);
    }
    

    Note that the body of the loop must perform some operation that changes the value of the boolean expression, otherwise the loop will continue indefinitely.

    For loops

    The syntax of a for loop is

    for (initialisation;boolean-expression;loop change) {
       repeated statements
    }
    

    For example (sum numbers 1 to 10):

    var sum=0;
    for (var i=1;i<=10;i=i+1) {
       sum = sum + i;
    }
    

    For loops are logically equivalent to while loops with this structure:

    initialisation
    while ( boolean-expression ) {
       repeated statements
       loop change
    }
    

    The for loop above is logically the same as:

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

    For loops are useful for operating on arrays when you know how many items are to be processed. For example to initialise an array or to process an array:

    var table=[];
    for (var i=0;i<1000;i++) table[i]=i*i;
    var sum=0;
    for (var i=0;i<table.length;i++) sum = sum + table[i];
    

    The syntax "i++" means "increment i", that is perform "i=i+1".

    Break and Continue
    The break statement can be used to terminate a loop early. This is useful if you want the loop termination test to be in the middle of a loop rather than at the top. When the break statement is encountered, the current inner-most loop terminates, and execution proceeds to the next statement after the end of the loop. For example, here we search a table for a given string:

    var match="";
    for (var i=0;i<stab.length;i++) {
       if (stab[i].indexOf("ABCD")>=0) {
          match = stab[i];
          break;
       }
    }
    // match contains the matched string or ""
    

    The continue statement can be used to skip over the remaining statements in the loop body without executing them. This can be useful to skip over items in a list which do not need processing. When the continue statement is encountered, execution proceeds to the loop change statement in a for loop, or to the next boolean expression evaluation in a while loop. For example, here we skip over array entries that cannot be processed:

    var sum=0;
    for (var i=0;i<itab.length;i++) {
       if (isNaN(itab[i]) || (itab[i] <= 0)) continue;
       itab[i] = Math.log(itab[i]);
       sum = sum + itab[i];
    }
    // sum contains sum of logs of legal values in table
    

    The function isNaN() returns true if the value is not a number. In this example, it would have been just as easy to use an "if" statement to execute the calculation conditionally.

Resources

Exercises

  1. Implement the "Number Properties" demonstration demo6-1.html. Modify the code ("ex6-1.html") to input real numbers rather than integers then add a test for whether the number is a whole number, and then only report odd/even for whole numbers.
  2. Implement the "Shopping List" demonstration demo6-2.html. Modify the code ("ex6-2.html") to sort the list before display and also to add a "Clear" button to empty the list. Advanced: only add an item to the list if it is not there already!
  3. Implement the "Prime Numbers" demonstration demo6-3.html. Compare the code with the Sieve of Eratosthenes algorithm as given on its Wikipedia page to determine how the algorithm finds the prime numbers.
  4. Implement ("ex6-4.html") a Body-Mass-Index (BMI) calculator. This should take a height (in m) and a weight (in kg) and return a BMI using the formula BMI=weight/(height*height). Next convert the numerical BMI score into a description using the labels: <18.5:underweight, 18.5-25:normal weight, 25-30:overweight, >30:obese.
  5. Implement a program ("ex6-5.html") to convert base 10 numbers to base 2 (i.e. decimal to binary). Here is the algorithm:
    1. input non-negative whole number
    2. If value is odd, store binary digit 1, else store binary digit 0.
    3. Divide value by 2, discarding remainder.
    4. If value is non-zero go to step b.
    5. Print out the binary digits in reverse order

    Make sure your program is robust to faulty input.

Homework

  1. Complete the exercises you did not finish in class.
  2. Implement a program to convert a number into a text description using a table. For example you might include in your program a table like this:

    var agemap=[ 
       { min:0, max:1, lbl:"infant" }, 
       { min:1, max:13, lbl:"child" }, 
       { min:13, max:18, lbl:"teen" }, 
       { min:18, max:65, lbl:"adult" }, 
       { min:65, max:120, lbl:"senior" } ];
    

    Then accept an age in years and report the matching text label, like this:

    Be sure to report an error if the given age does not match any label.

  3. Upload your answers to your exercises area on the course web space.
  4. Complete the Experiment Planning Guide for your proposed web experiment.

Word count: . Last modified: 14:19 02-Nov-2017.