Table of Contents

~~SLIDESHOW~~

Getting Started with JavaScript

Contact Hour 7: To be discussed on Tuesday 11th February, 2013.

Lecturer: Dr Chris P. Jobling.

JavaScript is the most commonly used language for achieving interactivity on the client side of a Web Application. It allows the browser to be scripted to enable interactive effects to be achieved without requiring a round-trip to the web server.


These slides and notes were originally based on Chapter 4 of Robert W. Sebasta, Programming the World-Wide Web, 3rd Edition, Addison Wesley, 2006. with additional examples and explanation from Chris Bates, Web Programming: Building Internet Applications, 3rd Edition, John Wiley, 2006.

Some of the examples are taken from the ABC of JavaScript: An Interactive JavaScript tutorial provided by OpenJS.

We will also illustrate the examples using the JavaScript console provided in the Firebug extension for Mozilla Firefox.

Getting started with JavaScript

This lecture gives a quick tour of the basics of JavaScript, introducing its most important concepts and constructs but leaving out many of the details of the language.

Contents of this Lecture

Learning Outcomes (1)

Don't forget to consider these as the basis for your PeerWise quizzes

At the end of this lecture you should be able to answer these questions:

  1. Describe briefly three major differences between Java and JavaScript.
  2. Describe briefly three major uses of JavaScript on the client side.
  3. Describe briefly the basic process of event-driven computation.
  4. What are the two categories of properties in JavaScript?
  5. Describe the two ways to embed a JavaScript script in an HTML document.

Learning Outcomes (2)

At the end of this lecture you should be able to answer these questions:

  1. What are the advantages and disadvantages of JavaScript?
  2. What are the two forms of JavaScript components?
  3. What are the five primitive data types in JavaScript?
  4. Do single-quoted string literals have any different characteristics than double-quoted string literals?

Learning Outcomes (3)

At the end of this lecture you should be able to answer these questions:

  1. In what circumstances would a variable have the value undefined?
  2. If the value undefined is used as a Boolean expression, is it interpreted as true or false?
  3. What value does typeof return for an object operand?

Learning Outcomes (4)

At the end of this lecture you should be able to answer these questions:

  1. What is the usual end-of-line punctuation for the string operand to document.write?
  2. What is the usual end-of-line punctuation for the string operand to alert?
  3. What is the usual end-of-line punctuation for the string operand to console.log?
  4. Describe the operation of the prompt method.

Overview of JavaScript

Java and JavaScript

Applications of JavaScript


<note> JavaScript is explicitly prohibited from accessing the local file store: it cannot write to the local hard drive nor read from it!

Unfortunately the implementation of DOM (a W3C standard) varies between browsers, so this is the main area that causes incompatibilities when writing JavaScript programs. </note>

Event-Driven Computation

Object Orientation and JavaScript

JavaScript is a functional programming language.

JavaScript is NOT an object-oriented programming language


<note> prototype-based inheritance – the new operator creates an instance of an object in which all properties are created and assigned to that object. Adding or removing properties has no effect on other instances of the same object that may exist at the same time. There is no possibility of a class variable that is shared by all objects </note>

JavaScript Objects

Benefits of JavaScript

JavaScript has a number of big benefits to anyone who wants to make their web site dynamic:

Problems with JavaScript

Although JavaScript looks like it should be a win-win for both developers and users, this is not always the case:

A Simple Script (1)

function describe() {
    var major = parseInt(navigator.appVersion);
    var minor = parseFloat(navigator.appVersion);
    var agent = navigator.userAgent.toLowerCase();
    document.write("<h1>Details in Popup</h1>");
    document.close();
    window.alert(agent + " " + major);
}

A Simple Script (2)

function farewell() {
    window.alert("Farewell and thanks for visiting");
}

Script in XHTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
   <head>...</head>
   <body>
     <div class="container">
       <h1>Our first JavaScript script</h1>
         :
       <div id="result"><!-- Result will be appended to this div--></div>
 
       <a href="../index.html" onclick="farewell();">Back to examples</a>
         :
     </div>
     <script language="javascript" type="text/javascript">
     //<![CDATA[
     <!--
        // Get details of browser
        // Say goodbye
     // -->
     // ]]>
     </script>
   </body>
</html>

There are some comments needed to explain this!

Firstly, the <script> element requires two attributes: the type attribute is the MIME-type for JavaScript files text/javascript; and language defines the language of the scripting language. These would seem to be equivalent but they are used for different purposes. The type attribute informs the browser what the content of the script tag is expected to be JavaScript code (particularly important if the script is uploaded from a file and the Web server does not properly identify the content as JavaScript). The language attribute tells the Browser to interpret the script with a JavaScript interpreter (it is possible, though probably not portable, to have other languages such as Perl, Python, TCL and for Internet Explorer VBScript).

Secondly, it is important that the script-code be protected from the HTML interpreter. In XML, the standard way to do this is to embed non-xml code in the <![CDATA[ … ]]> tags. This basically ensures that code symbols that would be special to XML (e.g. quotation marks, <, >, &) need not be replaced by character entities. For older versions of HTML, we need to use the HTML comment block to comment the script code <!– … –>. Finally, we need to protect XML/HTML from the scripting language itself by using script comment markers, e.g: //<![CDATA[, // –>, // ]]>.

<note>If you feel that this attention to detail is more than you want to deal with, it's worth noting that, as for CSS, a lot of these details disappear if the script is loaded from a separate file!</note>

Script in HTML5

<!DOCYPE html>
<html lang="en">
  <head>....</head>
   <body>
     <div class="container">
       <h1>Our first JavaScript script</h1>
         :
       <div id="result"><!-- Result will be appended to this div--></div>
 
       <a href="../index.html" onclick="farewell();">Back to examples</a>
         :
     </div>
     <script>
        // Get details of browser
        // Say goodbye
     </script>
   </body>
</html>

This is much simpler because:

  1. JavaScript is the default so we do not have to specify the language or the type attributes in the script tag.
  2. Modern browsers don't need the protection of HTML comments to prevent their intrepretation by the browser
  3. The CDATA block is only needed when the script is being used within the XML serialization of HTML5.

The Script Itself

The script itself defines the two functions describe() and farewell(). Function describe() is called when the document is loaded by the browser as defined by the onload attribute of the <body> element. Similarly, farewell() is called when the link “Back to examples” is clicked. This causes a click event to happen and the onclick attribute of the link causes farewell() to be called7). The attributes onload and onclick are two of the standard events that can be defined in HTML and which provide the simplest (although discouraged) way to communicate from the document to the script. We will describe many more later.

Script Execution

Run the script.


Here is the script in full:

<!DOCTYPE html>
 
<!-- hello_js_world.html: An Example JavaScript script -->
 
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>Our first JavaScript script</title>
        <meta name="viewport" content="width=device-width">
 
        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/bootstrap-responsive.min.css">
        <link rel="stylesheet" href="css/main.css">
 
        <script src="js/vendor/modernizr-2.6.2-respond-1.1.0.min.js"></script>
    </head>
    <body onload="describe()">
        <!--[if lt IE 7]>
            <p class="chromeframe">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">activate Google Chrome Frame</a> to improve your experience.</p>
        <![endif]-->
 
        <div class="container">
            <h1>Our first JavaScript script</h1>
 
            <p>Use this file as a template for your own.
 
 
            <div id="result"></div>
 
            <a href="../index.html" onclick="farewell();">Back to examples</a>
 
            <hr>
            <footer>
                <p>&copy; Swansea University 2013</p>
            </footer>
 
        </div> <!-- /container -->
 
       <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
        <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.9.0.min.js"><\/script>')</script>
 
        <script src="js/vendor/bootstrap.min.js"></script>
 
        <script src="js/plugins.js"></script>
 
        <script>
        // The actual JavaScript code goes here
 
        // Define point in DOM where result will be appended as HTML
        var result_element = $('#result');
 
        function describe() {
           var major = parseInt(navigator.appVersion);
           var minor = parseFloat(navigator.appVersion);
           var agent = navigator.userAgent.toLowerCase();
           result_element.append("<h2>Details in Popup<\/h3>");
           window.alert(agent + " " + major);
         }
 
         function farewell() {
           window.alert("Farewell and thanks for visiting");
         }
         </script>
    </body>
</html>

Please note that most of this is required by the Twitter Bootstrap template. You should pay attention to the final script element. A small amount of jQuery magic has been used to avoid the destructive use of the document.write method to write the text Details in Popup into the document.

General Syntactic Characteristics

      <script>
      -- JavaScript script -
      </script>
      <script src = "myScript.js"></script>

Playing with JavaScript

At least 3 ways:

A JavaScript Playground

Provided by jsFiddle. Use this and the developer tools console to play with JavaScript.

Demo of the Console

Identifiers and Comments


The 25 reserved words of JavaScript are illustrated in the table below.

break delete function return typeof
case do if switch var
catch else in this void
continue finally instanceof throw while
default for new try with

Primitives, Operations, and Expressions

Numbers and strings

Special primitives

Variables and declarations

      var sum = 0
      today = "Monday"
      flag = false;

In this example the variable sum is declared explicitly by use of the var keyword, whereas the variables today and flag are declared implicitly. If the variables do yet yet exist they will be created and assigned the values that appear on the right-hand side of the assignment =. If a variable already exists, it will take on the new value even if the value is a different type from the variable that was previously assigned.

<note> Please note that modern usage is to explicitly declare all variables using var before they are used. If you don't JavaScript will make the variable global and this will often cause unexpected behaviour! Modern style would declare the examples above8):

var 
 sum = 0,
 today = "Monday",
 flag = false;

</note>

More on Variables and Operators

Visit Chapter 2 of Eloquent JavaScript.

Numbers and maths

The Number Object

String operators

Explicit String conversions

  1. Use the String and Number constructors
  2. Use toString method of numbers
  3. Use parseInt and parseFloat on strings

String properties and methods

Primitives, Operations, and Expressions (continued)

The Date Object

Screen Output and Keyboard Input

Screen Output using the Document Object

      document.write("Answer: " + result + "<br />");

Console output


In Firefox and Chrome developer tools there is a JavaScript console. You can write to it using:

      console.log("Answer: " + result);

It's better than document.write because as well as outputting string versions of its arguments, it will actually output objects that you can browse.

Screen Output: jQuery magic

<div id="result">
</div>
$('#result').append('<p>The html you would have written with <code>document.write()

</p>'); </code>

<div id="result">
<p>The html you would have written with <code>document.write()

</p> </div> </code>

Screen Output: alert

Input: confirm

Boolean (yes,no: true/false):

Input: prompt

Strings:


You can only enter a string this way but by use of coercion, or better still the parseInt and parseFloat functions, you can convert strings to numbers.

Another example


<!DOCTYPE html>
 
<!-- roots.html 
     Compute the real roots of a given quadratic
     equation. If the roots are imaginary, this script
     displays NaN, because that is what results from 
     taking the square root of a negative number
     -->
 
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>Real roots of a quadratic equation</title>
        <meta name="viewport" content="width=device-width">
 
        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/bootstrap-responsive.min.css">
        <link rel="stylesheet" href="css/main.css">
 
        <script src="js/vendor/modernizr-2.6.2-respond-1.1.0.min.js"></script>
    </head>
    <body>
        <!--[if lt IE 7]>
            <p class="chromeframe">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">activate Google Chrome Frame</a> to improve your experience.</p>
        <![endif]-->
 
        <div class="container">
            <h1>Real roots of a quadratic equation</h1>
 
            <p>Use this file as a template for your own JavaScript experiments.
 
 
            <div id="result"><!-- Result will be appended to this div--></div>
 
            <a href="../index.html">Back to examples</a>
 
            <hr>
            <footer>
                <p>&copy; Swansea University 2013</p>
            </footer>
 
        </div> <!-- /container -->
 
       <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
        <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.9.0.min.js"><\/script>')</script>
 
        <script src="js/vendor/bootstrap.min.js"></script>
 
        <script src="js/plugins.js"></script>
 
        <script>
            // The actual JavaScript code goes here
 
            // Declare variables we'll be using
            var 
              result_element,
              a, b, c,
              root_part, denom,
              root1, root2;
 
            // Find point in DOM where result will be appended as HTML
            result_element = $('#result');
 
            // Get the coefficients of the equation from the user
            a = prompt("What is the value of 'a'? \n", "1");
            b = prompt("What is the value of 'b'? \n", "3");
            c = prompt("What is the value of 'c'? \n", "2");
 
            // Compute the square root and denominator of the result
            root_part = Math.sqrt(b * b - 4.0 * a * c);
            denom = 2.0 * a;
 
            // Compute and display the two roots
            root1 = (-b + root_part) / denom;
            root2 = (-b - root_part) / denom;
 
            // Display results in page
            result_element.append("<p>The first root is: " + root1 + "<br />");
            result_element.append("The second root is: " + root2 + "</p>"); 
         </script>
    </body>
</html>

This is the key bit:

// Declare variables we'll be using
var 
    result_element,
    a, b, c,
    root_part, denom,
    root1, root2;
 
// Find point in DOM where result will be appended as HTML
result_element = $('#result');
 
// Get the coefficients of the equation from the user
a = prompt("What is the value of 'a'? \n", "1");
b = prompt("What is the value of 'b'? \n", "3");
c = prompt("What is the value of 'c'? \n", "2");
 
// Compute the square root and denominator of the result
root_part = Math.sqrt(b * b - 4.0 * a * c);
denom = 2.0 * a;
 
// Compute and display the two roots
root1 = (-b + root_part) / denom;
root2 = (-b - root_part) / denom;
 
// Display results in page
result_element.append("<p>The first root is: " + root1 + "<br />");
result_element.append("The second root is: " + root2 + "</p>"); 

Summary of this Lecture

Getting started with JavaScript

Learning Outcomes (1)

Don't forget to consider these as the basis for your PeerWise quizzes

At the end of this lecture you should be able to answer these questions:

  1. Describe briefly three major differences between Java and JavaScript.
  2. Describe briefly three major uses of JavaScript on the client side.
  3. Describe briefly the basic process of event-driven computation.
  4. What are the two categories of properties in JavaScript?
  5. Describe the two ways to embed a JavaScript script in an HTML document.

Learning Outcomes (2)

At the end of this lecture you should be able to answer these questions:

  1. What are the advantages and disadvantages of JavaScript?
  2. What are the two forms of JavaScript components?
  3. What are the five primitive data types in JavaScript?
  4. Do single-quoted string literals have any different characteristics than double-quoted string literals?

Learning Outcomes (3)

At the end of this lecture you should be able to answer these questions:

  1. In what circumstances would a variable have the value undefined?
  2. If the value undefined is used as a Boolean expression, is it interpreted as true or false?
  3. What value does typeof return for an object operand?

Learning Outcomes (4)

At the end of this lecture you should be able to answer these questions:

  1. What is the usual end-of-line punctuation for the string operand to document.write?
  2. What is the usual end-of-line punctuation for the string operand to alert?
  3. What is the usual end-of-line punctuation for the string operand to console.log?
  4. Describe the operation of the prompt method.

There are many more review questions available.

Further Reading

The Introduction and the opening of Chapter 1 of Eloquent JavaScript cover much the same material as these notes and include some interactive exercises that you can try.

Exercise

Write, test and debug (if necessary) HTML5 files that include JavaScript scripts for the following problems. When required to write functions, you must include a script to test the function with at least two different data sets.

  1. Modify the roots programme so that it deals properly with numbers and uses console.log for output.
  2. Input: Three numbers, using prompt to get each. Output: The largest of the three input numbers. Hint: Use the predefined function Math.max.

What's Next?

Programming in JavaScript

Previous Lecture | home | Next Lecture

1)
Graphics support via the new Canvas feature and associated JavaScript APIs was added in HTML 5 and is available in all modern browsers
2)
Object has no properties!
3)
JavaScript can neither read from the your local hard drive nor write to it and you cannot get a virus infection directly from JavaScript.
4)
Although the situtaion is much better now as HTML5 is more prescriptive about what the DOM should be and what browsers should do in given situations.
5)
Again modern browser developers have put a lot of effort into making script engines more efficient. Conversely, web applications rely more and more on scripts, so this speed advantage may not last long
6)
Two popular libraries are jQuery and BackboneJS.
7)
The original example used onunload on the body tag to calle farewell(). This doesn't work with modern browsers because they typically prevent pop-ups when a page us unloaded (i.e. reloaded or replaced by another document) because of the annoying way that unscrupulous website owners would use pop-ups to direct you to another site when trying to leave.
8)
Pay particular attention to the punctuation – this is executed as a single statement
9)
This is now standard in most browsers.