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:
- Describe briefly three major differences between Java and JavaScript.
- Describe briefly three major uses of JavaScript on the client side.
- Describe briefly the basic process of event-driven computation.
- What are the two categories of properties in JavaScript?
- 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:
- What are the advantages and disadvantages of JavaScript?
- What are the two forms of JavaScript components?
- What are the five primitive data types in JavaScript?
- 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:
- In what circumstances would a variable have the value
undefined
? - If the value undefined is used as a Boolean expression, is it interpreted as
true
orfalse
? - What value does
typeof
return for anobject
operand?
Learning Outcomes (4)
At the end of this lecture you should be able to answer these questions:
- What is the usual end-of-line punctuation for the string operand to
document.write
? - What is the usual end-of-line punctuation for the string operand to
alert
? - What is the usual end-of-line punctuation for the string operand to
console.log
? - Describe the operation of the
prompt
method.
Overview of JavaScript
- Originally developed by Netscape, as LiveScript
- Became a joint venture of Netscape and Sun in 1995, renamed JavaScript
- Now standardized by the European Computer Manufacturers Association as ECMA-262 (also ISO 16262)
- We'll call collections of JavaScript code scripts, not programs
Java and JavaScript
- JavaScript and Java are only related through syntax
- JavaScript is dynamically typed
- JavaScript's support for objects is very different
Applications of JavaScript
- JavaScript can be used to replace some of what is typically done with applets (including graphics1))
- JavaScript can be used to replace some of what is done with CGI (including limited file operations and networking)
- User interactions through forms are easy
- The Document Object Model (DOM) makes it possible to support dynamic HTML documents with JavaScript
- Many of the new features added to HTML5 are actually JavaScript features!
<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
- User interactions with HTML documents in JavaScript use the event-driven model of computation
- User interactions with HTML elements can be used to trigger execution of scripts
Object Orientation and JavaScript
JavaScript is a functional programming language.
JavaScript is NOT an object-oriented programming language
- JavaScript does not support class-based inheritance
- JavaScript does not support polymorphism
- JavaScript has prototype-based inheritance, which is much different
<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
- JavaScript objects are collections of properties, which are like the members of classes in Java and C++
- JavaScript has primitives for simple types
- The root object in JavaScript is Object – all objects are derived from Object2)
- All JavaScript objects are accessed through references
- Properties can be object references, primitives or functions
- Properties can be added and deleted at any time!
Benefits of JavaScript
JavaScript has a number of big benefits to anyone who wants to make their web site dynamic:
- It is widely supported in Web browsers.
- It gives easy access to the document objects (elements and attributes) and can manipulate most of them.
- It can give interesting animations without the long download times associated with many multimedia data types.
- It is relatively secure.3)
- Web surfers do not need a special plug-in to use your scripts
Problems with JavaScript
Although JavaScript looks like it should be a win-win for both developers and users, this is not always the case:
- Most scripts rely upon manipulating elements of the DOM. Support for a standard set of DOM objects currently does not exist4) and access to objects differs from Browser to Browser.
- If your script does not work then your web page is useless!
- Because of the problems of broken scripts, many Web surfers disable JavaScript support in their browser.
- Scripts can run slowly and complex scripts take a long time to start up5).
- To overcome browser issues, modern developers make use of libraries that provide better abstractions of the DOM and allow separation of concerns between the application data and the display of that data in HTML6)
A Simple Script (1)
- Get details of browser
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)
- Say goodbye
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:
- JavaScript is the default so we do not have to specify the
language
or thetype
attributes in thescript
tag. - Modern browsers don't need the protection of HTML comments to prevent their intrepretation by the browser
- 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>© 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
- For this module, all JavaScript scripts will be embedded in HTML5 documents
- Either directly, as in
<script> -- JavaScript script - </script>
- Or indirectly, as a file specified in the src attribute of
<script>
, as in
<script src = "myScript.js"></script>
Playing with JavaScript
At least 3 ways:
- Put code in
<script>
tags or link code to<script>
tags in an HTML page. Reload page to execute. - Better: Run code inside jsFiddle
- Best: run code in developer tools and use JavaScript console. Gives full access to the HTML, CSS and code as it will be when deployed.
A JavaScript Playground
Provided by jsFiddle. Use this and the developer tools console to play with JavaScript.
Demo of the Console
Identifiers and Comments
- Identifier form: identifiers begin with a letter, the dollar sign (
$
) or underscore (_
), followed by any number of letters, underscores, dollar signs and digits - Identifiers are case sensitive
- 25 reserved words, plus future reserved words should not be used
- Comments: both
//
and/* . . . */
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
- All primitive values have one of the five primitive types: Number, String, Boolean, Undefined, or Null
- Number, String, and Boolean have wrapper objects (
Number
,String
, andBoolean
) - In the cases of Number and String, primitive values and objects are (automatically) coerced back and forth so that primitive values can be treated essentially as if they were objects
Numbers and strings
- Numeric literals – just like Java
- except that all numeric values are stored in double-precision floating point
- String literals are delimited by either
'
or"
- Can include escape sequences (e.g.,
\t
) - All String literals are primitive values
Special primitives
- Boolean values are
true
andfalse
- The only Null value is
null
- The only Undefined value is
undefined
Variables and declarations
- JavaScript is dynamically typed – any variable can be used for anything (primitive value or reference to any object)
- The interpreter determines the type of a particular occurrence of a variable at run-time
- Variables can be either implicitly or explicitly declared
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
- Numeric operators –
++
,–
,+
,-
,*
,/
,%
- All operations operate in double precision
- Same precedence and associativity as Java
- The
Math
object providesfloor
,round
,max
,min
, trig functions, etc. e.g.,Math.cos(x)
The Number Object
- Some useful properties:
MAX_VALUE
,MIN_VALUE
,NaN
,POSITIVE_INFINITY
,NEGATIVE_INFINITY
,PI
- e.g.,
Number.MAX_VALUE
- An arithmetic operation that creates overflow returns
NaN
NaN
is not equal to any number, not even itselfNaN == NaN
is alwaysfalse
!- Test for it with
isNaN(x)
- Number object has the method,
toString
which converts number to a string.
String operators
- String concatenation operator is
+
- Coercions
- Concatenation coerces numbers to strings
- Numeric operators (other than
+
) coerce strings to numbers (if either operand of+
is a string, it is assumed to be concatenation)
- Conversions from strings to numbers that do not work return
NaN
Explicit String conversions
- Use the String and Number constructors
- Use
toString
method of numbers - Use
parseInt
andparseFloat
on strings
String properties and methods
length
e.g.,var len = str1.length;
(a property)charAt(position)
e.g.,str.charAt(3)
indexOf(string)
e.g.,str.indexOf('B')
substring(from, to)
e.g., str.substring(1, 3)
toLowerCase()
e.g.,str.toLowerCase()
Primitives, Operations, and Expressions (continued)
- The
typeof
operator- Returns
“number”
,“string”
, or“boolean”
for primitives - returns
“object”
for objects,null
for Null, and“undefined”
for Undefined
- Assignment statements
- just like C++ and Java
The Date Object
- Create one with the Date constructor (no parameters)
- Local time methods of Date:
toLocaleString
– returns a string of the dategetDate
– returns the day of the monthgetMonth
– returns the month of the year (0—11)getDay
– returns the day of the week (0—6)getFullYear
– returns the yeargetTime
– returns the number of milliseconds since January 1, 1970getHours
– returns the hour (0—23)getMinutes
– returns the minutes (0—59)getMilliseconds
– returns the millisecond (0—999)
Screen Output and Keyboard Input
- The JavaScript model for the HTML document is the Document object
- The model for the browser display window is the Window object
- The model for the browser itself is the Navigator object
- The Window object has two properties,
document
andwindow
, which refer to the Document and Window objects, respectively
Screen Output using the Document Object
- The Document object has a method,
write
, which dynamically creates (HTML) content - The parameter is a string, often concatenated from parts, some of which are variables. e.g:
document.write("Answer: " + result + "<br />");
- The parameter is sent to the browser, so it can be anything that can appear in an HTML document (
<br />
, but not\n
)
Console output
- Warning document.write() overwrites any HTML content that might have existed before the call.
- For this reason, you should never use it.
- Forget I told you about it!
- If you want the equivalent to a print statement, e.g. for debugging, use the
console.log
9) function. - In the examples I use a small piece of jQuery magic to append the results to the existing document rather than overwriting the whole document.
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
- HTML placeholder
<div id="result"> </div>
- Output function
$('#result').append('<p>The html you would have written with <code>document.write()
</p>'); </code>
- Result
<div id="result"> <p>The html you would have written with <code>document.write()
</p> </div> </code>
Screen Output: alert
- The Window object has three methods for creating dialogue boxes,
alert
,confirm
, andprompt
alert(“Hey! \n”);
- Parameter is plain text, not HTML
- Opens a dialogue box which displays the parameter string and an OK button
- It waits for the user to press the OK button
Input: confirm
Boolean (yes,no: true/false):
confirm(“Do you want to continue?”);
- Opens a dialogue box and displays the parameter and two buttons, OK and Cancel
- Returns a Boolean value, depending on which button was pressed (it waits for one)
Input: prompt
Strings:
prompt(“What is your name?”, “”);
- Opens a dialogue box and displays its string parameter, along with a text box and two buttons,
OK
andCancel
- The second parameter is for a default response if the user presses
OK
without typing a response in the text box (waits forOK
)
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
- Roots of a quadratic equation roots.html.
<!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>© 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:
- Describe briefly three major differences between Java and JavaScript.
- Describe briefly three major uses of JavaScript on the client side.
- Describe briefly the basic process of event-driven computation.
- What are the two categories of properties in JavaScript?
- 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:
- What are the advantages and disadvantages of JavaScript?
- What are the two forms of JavaScript components?
- What are the five primitive data types in JavaScript?
- 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:
- In what circumstances would a variable have the value
undefined
? - If the value undefined is used as a Boolean expression, is it interpreted as
true
orfalse
? - What value does
typeof
return for anobject
operand?
Learning Outcomes (4)
At the end of this lecture you should be able to answer these questions:
- What is the usual end-of-line punctuation for the string operand to
document.write
? - What is the usual end-of-line punctuation for the string operand to
alert
? - What is the usual end-of-line punctuation for the string operand to
console.log
? - 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.
- Modify the roots programme so that it deals properly with numbers and uses
console.log
for output. - 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
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.