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

5. Javascript Language Part 1

Learning Objectives

By the end of the session you should:

Topics

  1. Types & literal values
  2. Numeric

    Numeric values in Javascript hold real ("floating-point") numbers, approximately in the range

    -10308 … -10-324, 0, 10-324 … 10308

    Numbers are stored with an approximate precision of 15 digits.

    Whole numbers (integers) may only be stored exactly between -9007199254740992 … 9007199254740992.

    Examples of number literals:

    23, -102, 2.678, 3.45E10, 5.67E-4

    String

    Javascript strings are sequences of zero or more Unicode characters, for example:

    "Hello", 'One Two Three', "中国", "juːnɪkəʊd", "A", ""

    Note that "A" is a string containing one character, and that "" is a string containing no characters.

    Strings may be enclosed in single or double quotes. To include a quote mark within a string, you can use \' or \". To include a "newline" in a string, you can use \n. To include backslash in a string, you can use \\.

    Boolean

    A boolean value can only be either true or false.

    Object

    All other elements of Javascript, such as functions or elements of web pages are called objects. We will see that all objects can be manipulated in Javascript.

  3. Variables & assignment
  4. Variables are named locations in memory where you can store information (in the form of numbers, strings, booleans or objects).

    Variables are identified with names. The name of a variable is a combination of letters, digits, the underscore character (_) and the dollar sign ($), although the first character may not be a number. The case of letters matters, the variable fred is different from Fred. A number of words are reserved for the language syntax and may not be used to name variables (e.g. "function", "var", "true", "false").

    Variables should be declared before use. This guards against typing mistakes! Normally you declare a variable at the same time as you first use it. It is good practice to allocate each variable a value at declaration, otherwise the contents of the variable is undefined.

    Variables can be declared with the var statement:

    var mynumber;
    var mystring;
    var myboolean;
    

    You do not need to specify the type of the variable in the declaration. Javascript will assign a type when you first use it, and will change the type as required. To initialise each variable to a specific value in the declaration, use the syntax:

    var mynumber=100;
    var mystring="Javascript";
    var myboolean=false;
    

    Once a variable has been declared you can change its contents using an assignment statement:

    variable = expression
    

    For example:

    mynumber=25;
    mystring="Hello";
    myboolean=true;
    

    Note that assignment is not the same as the test for equality. You should read these statements as "mynumber becomes 25", "mystring becomes Hello", "myboolean becomes true".

    Expressions are defined next.

  5. Expressions
  6. Expressions are combinations of literal values, variable values and operators which can be evaluated to give an arithmetic, string or boolean result.

    Arithmetic

    The most common arithmetic operators

    NameExampleDescription
    +a+bAdd numbers,
    Concatenate strings
    -a-bSubtract
    *a*bMultiply
    /a/bDivide
    %a%bModulus (Remainder after integer division)
    ()a*(b+c)Group
    ++a++Increment
    --a--Decrement

    Relational

    The most common relational operators

    NameExampleDescription
    <a<5Less than
    <=0<=bLess than or equal
    >c>0Greater than
    >=100>=aGreater than or equal
    ==a==10Equal
    !=b!=100Not equal

    Logical

    The most common logical operators

    NameExampleDescription
    &&(1<=a)&&(a<=10)And
    ||(a<1)||(a>10)Or
    !!((a<1)||(a>10))Not

    Mathematics

    The most common math functions. These properties and methods are accessed through the global "Math" object.

    NameExampleDescription
    Math.PIa=2*Math.PIValue of π
    Math.abs(x)a=Math.abs(b) Returns the absolute value of a number.
    Math.ceil(x)ival=Math.ceil(rval) Returns the smallest integer greater than or equal to a number.
    Math.exp(x)e10=Math.exp(10) Returns ex, where x is the argument, and e is Euler's number (2.718...), the base of the natural logarithm.
    Math.floor(x)ival=Math.floor(rval) Returns the largest integer less than or equal to a number.
    Math.log(x)l=Math.log(10) Returns the natural logarithm (loge, also ln) of a number.
    Math.log10(x)l=math.log10(50) Returns the base 10 logarithm (log10) of x.
    Math.max([x[,y[,…]]])c=Math.max(a,b) Returns the largest of a list of numbers.
    Math.min([x[,y[,…]]])c=Math.min(a,b) Returns the smallest of a list of numbers.
    Math.pow(x,y)p=Math.pow(10,1.2) Returns x to the power y, that is, xy.
    Math.random()r=Math.random() Returns a pseudo-random number between 0 and 1 (0 <= r < 1).
    Math.round(x)ival=Math.round(rval) Returns the value of a number rounded to the nearest integer.
    Math.sqrt(x)r=Math.sqrt(2) Returns the positive square root of a number.
    Math.trunc(x)ival=Math.trunc(rval) Returns the integral part of the number x, removing any fractional digits.

    The Math object also includes all the usual trigonometric functions: Math.sin(), Math.cos(), Math.tan(), etc.

    String methods

    A method is the name given to a function that is tied to a particular class of objects. To use these string methods you must start with a string object and then apply these functions using the "dot" operator. Here is an example. The toLowerCase() method returns the string converted to lower case, but given a string variable with the name mystring you would not write toLowerCase(mystring), but instead mystring.toLowerCase(). This is because the toLowerCase() method belongs to the class of string objects rather than being a global function.

    These are some of the more frequently used string methods with examples using a string variable str.

    NameExampleDescription
    charAt(index)ch=str.charAt(5)Returns the character at the specified index. Note that the first character has index 0.
    indexOf(term)idx=str.indexOf("x")Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.
    lastIndexOf(term)idx=str.lastIndexOf("ABC")Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.
    slice(start,stop)xtr=str.slice(2,4)Extracts a section of a string and returns a new string. Extraction starts at character index start and ends just before character index stop. If stop is missing, returns rest of string to end.
    substr(start,num)xtr=str.substr(2,2)Returns the characters in a string beginning at the specified location through the specified number of characters. If num is missing, returns rest of string to end. If start is negative the index is counted from the end of the string backwards.
    toLowerCase()lwr=str.toLowerCase()Returns the string value converted to lower case.
    toUpperCase()upr=str.toUpperCase()Returns the string value converted to uppercase.

    In addition you can obtain the length of any string expression using its length property:

    var str="Hello.";
    console.log("length of string str is "+str.length);
    

    Would print 'length of string str is 6'.

    The eval() function

    The eval() function takes a string argument and evaluates it as if it were a JavaScript expression. This can be useful when you want to test how expressions are evaluated. You can experiment with the use of eval() in the form below, which has the following event handler at its heart:

    function button1click() {
       document.getElementById("answer").innerHTML = 
          eval(document.getElementById("expression").value);
    }
    

    Javascript Expression Evaluator

    =

  7. Function declarations and calls
  8. Function definition

    A function is a block of Javascript code which is given a name and an optional set of parameters. When called, the code in the function is executed and may return a value.

    A function declaration has the syntax:

    function name ( parameter-list ) {
        statements
    }
    

    The name is used to identify the function and must be unique in the script. The parameter list is a comma-separated list of dummy variables, these are the names used within the function for the expressions passed in the function call. The block of statements must be bracketed with {} and statements are separated from one another by semi-colons ";". If you want the function to return a value use the statement return expression. When this statement is executed the function call is terminated and the value of the expression is returned to the calling expression.

    Here are some example definitions:

    function doprint(val) {
        console.log("Value of variable = " + val);
    }
    function square(x) {
        return(x*x);
    }
    function hypot(a,b) {
       var a2=a*a;
       var b2=b*b;
       return(Math.sqrt(a2+b2));
    }
    

    Functions are called using the syntax name ( expression-list ). Items in the expression list are separated by commas. How the functions above may be called:

    var x=10;
    doprint(x);
    var y=square(10);
    var h=hypot(x,y);
    

    Functions may also be defined using an assignment statement with the syntax:

    name = function ( parameter-list ) {
        statements
    }
    

    for example:

    square = function (x) { return(x*x); }
    

    The two forms of function declaration are equivalent.

    Variable scope

    When variables are declared within a function, they may only be accessed within that function, they do not exist except when the function is being called. We say that these variables have local scope. Variables declared outside any function can be accessed anywhere, both within and outside function blocks. We say that such variables have global scope.

    Global variables are important as a means to preserve data values between events. While local variables are initialised and their old contents lost each time their function is called; global variables are initialised when the page is loaded and retain their values until the page is unloaded.

    Here is a complete demonstration of the importance of scope:

    <!DOCTYPE html>
    <html>
    <head>
    <title>Variable Scope</title>
    <script>
    // global scope
    var gtotal=0;
    function buttonclick() {
      // local scope
      var ltotal=0;
      gtotal = gtotal+1;
      ltotal = ltotal+1;
      document.getElementById("totals").innerHTML=
        "Global total = " + gtotal + " Local total = " + ltotal;
    }
    </script>
    </head>
    <body>
      <h1>Variable Scope</h1>
      <p><button onclick="buttonclick()">Click to add 1</button>
      <p><span id="totals"></span>
    </body>
    </html>
    

    When the button is repeatedly pressed, the global total continues to increase, while the local total remains at 1.

    Some useful built-in functions & methods

    NameExampleDescription
    evala=eval("123*456")Evaluates the Javascript code in the given string
    parseIntival=parseInt("123")Converts a string to an integer
    parseFloatrval=parseFloat("3.14159")Converts a string to a floating point number
    toExponential(n)str=num.toExponential()Formats a number in exponential notation, the optional argument sets the number of digits after the decimal point
    toFixed(n)str=num.toFixed(3)Formats a number with n digits after the decimal point
    toPrecision(n)str=num.toPrecision(10)Formats a number using n characters (1<=n<=21)
    toString()str=num.toString()Converts a number to a string

Resources

Exercises

  1. Implement demonstration demo5-1.html: JavaScript Expression Evaluation. Use this to demonstrate the following:
    1. Arithmetic operators (e.g. 3+4*5, (3+4)*5, 20%3, ...)
    2. String concatenation (e.g. "Hello" + "Mark", ...)
    3. Math functions (e.g. Math.sqrt(3*3+4*4), Math.PI*Math.pow(5,2), ...)
    4. String methods (e.g. "abcdef".toUpperCase(), "abcdef".indexOf("d"), ...)
  2. Implement the adding machine application demo5-2.html. Modify the code ("ex5-2.html") to allow multiplication as well as addition, and also add a Reset button to reset value to zero.
  3. Implement the string method demonstration demo5-3.html. Modify the code ("ex5-3.html") to also demonstrate the indexOf() and lastIndexOf() methods too.
  4. Write an interactive application ("ex5-4.html") that inter-converts between linear values and decibels. The formulae are: db=20.log10(linear) and linear=10db/20.
  5. Write an interactive application ("ex5-5.html") that inter-converts between centimetres and feet & inches. The formulae are: inches=cm/2.54 and cm=2.54*inches.
  6. Write an interactive application ("ex5-6.html") that displays a random alphabetic letter when a button is pressed. Hint: generate a random integer between 1 and 26 with Math.random(), then select a character from the alphabet with the string method charAt(index).

Homework

  1. Complete the exercises you did not finish in class.
  2. Watch an introductory video on the syntax of the JavaScript language such as JavaScript Essential Training.
  3. Work through the part of any text tutorial on JavaScript that covers the topics we have addressed today, such as the W3Schools tutorial or JavaScript first steps guide.
  4. The JavaScript Date object can be used to get the current date and time. Read up about the Date object on the web then write a program that displays the current day and time in the format: "Sat Oct 31 2015 14:15:31". Be sure to nicely style the display of the date. Advanced: you can use the setTimeout() function to update the date and time each second; read about how to do this on the web, then update your program to turn it into a dynamic clock, like this:
  5. Upload your answers to your exercises area on the course web space.

Word count: . Last modified: 11:09 03-Nov-2017.