FIT3084: JavaScript, Part 1


In the previous lecture:

In this lecture:


References

Sebasta, R. W. Programming the World Wide Web, 2009 / 5th edn, Pearson, chapt. 4


What is Javascript?

JavaScript is not Java! But it has (had) other names like: Livescript, JScript and ECMAScript.


JavaScript Syntax

JavaScript contains primitive types Number, String, Boolean, Undefined and Null, as well as predefined, corresponding wrapper object types of the same names.

The wrapper types contain a data-member holding a primitive value of their corresponding type, and methods for use on that type. Examples below...


Strings

"This is a string" and 'This is a string'

'T' 'h' "e" "s" "e" "are strings too!"

There is no distinction between single characters and strings

Single quotes are useful:

You can escape a quotation mark using backslash:

\n linefeed (UNIX newline), \r carriage return (Macintosh newline) \t (tab)

Strings may be concatenated using the + operator.

The escape() and unescape() global functions convert strings to URL encoded versions and vica-versa. For example:



Numbers

Math Object

The Math object contains methods for operating on Number objects, as well as some properties, e.g. Math.sin(x) or Math.round(x)



Booleans

Keywords true and false

These are not the same as 1 and 0!



Comments

// This is a comment to the end of a line

/* This is a comment
which spans more
than one line */

Some very old browsers do not recognise the <script> tags and will reproduce their contents as text (i.e. the JavaScript code will be displayed in the browser window instead of being executed.

The XHTML validator will also struggle if the JavaScript contains recognisable tags in its output, sometimes causing validation errors.

To avoid these problems, encapsulate your JavaScript code in XHTML comments between an XHTML comment openeer <!-- and a JavaScript comment followed by the XHTML comment closer on its own line // -->

Like this...

<!--

JavaScript code

// -->



Type Conversion

Type conversion may be implicit (coercion) or explicit. Most commonly these conversions are between Numbers and Strings.

If either operand of a + operator is a string, the other operator is implicitly converted to a string...

Strings are automatically converted to numbers if you try to perform arithmetic with them...

Strings containing numbers can be explicitly converted to Numbers and vice versa using constructors...

Strings can be converted to numbers of specific bases also...

Also see parseInt(), parseFloat(). These check a string parameter to see if its leading charcaters can be converted to an Integer or Float respectively.



Variables & Assignment

JavaScript is weakly typed hence the statements...

...work just fine one after another even though one assigns myVariable to a string and the other to a number!

Variable names must be alphanumeric characters starting with a letter or underscore. (Case is significant)

Variables do not need to be declared before use but it is important to declare local variables in a function to avoid overwriting global variables of the same name!



Operators & Expressions

The following operators and expressions are valid in JavaScript, just as they are in the C programming language.



Comparisons & Conditional Statements

The following are valid in JavaScript, just as they are in the C programming language.



Loops

The following are valid in JavaScript, just as they are in the C programming language.



Functions

JavaScript function definitions are made using the function keyword.

JavaScript function definitions do not include the return type.

Sample function definitions

Functions are called using C syntax:

Remember to declare local variables to avoid over-writing globals!

Functions can be assigned to variables. (The variable is a reference to the function)



Arrays

To make a new array...

Also, JavaScript has some pre-defined arrays:

Array indices begin at 0.

Arrays are indexed using square brackets [ and ].

Arrays have a read only length property which holds the size of the array.

Sample array access:



Objects

JavaScript is not truly object oriented although it is "object based" – JavaScript does not support class-based inheritance, it employs prototype-based inheritance (which we won't discuss).

JavaScript "objects" contain data parts (properties) and functions (methods).

Creating a JavaScript Object

Create a constructor function with the same name as the object type.

The constructor can have any number of arguments.

Constructors return no result.

Constructors are responsible for defining the data and method members of an object.


Remember that variables can be references to functions too!

Call the new operator to create instances of the object.

Accessing Object Members

Access works just like access to a C struct's fields.


JavaScript objects are really just arrays indexed by strings (rather than integers).

A special for ... in loop runs through the properties of an object in the order they were created.


JavaScript uses...

Space Invaders in JavaScript
Hierarchical Menus in JavaScript
web form
Form Validation (often using regular expressions...)

Regular Expressions

JavaScript pattern matching is based on the regular expressions of Perl.

These are commonly used for form validation (checking for valid postal addresses, phone numbers, email addresses, postcodes etc.)

Simple pattern matching is achieved using the String search method.

A period "." matches any character except a newline. To match a period, escape it with a backslash \

Characters between [ and ] indicate alternative matches.

A ^ character specified at the start of a class of characters inverts that set.

A - character indicates a range of characters for matches.

Whitespace can be detected.

Patterns can be tested for a forced match at the beginning of a string with a leading ^ symbol, or the end of a string with a trailing $ symbol.

Other characters to research include * + ? { }


 

A Google Maps example

Interactive maps like Google maps - click & drag to pan, click controls to zoom

JavaScript source utilises Google's API for its map software to display the above map:

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=SiteSpecificCode" type="text/javascript">         
   if (GBrowserIsCompatible())
   {
      var map = new GMap2(document.getElementById("map"));
      map.setCenter(new GLatLng(-37.91270348039777, 145.1369800497491), 15);
      map.setMapType(G_SATELLITE_MAP);
      map.openInfoWindow(map.getCenter(), document.createTextNode("Monash University -- here we are!"));
   
      var mapControl = new GSmallZoomControl();
      map.addControl(mapControl);
   }
</script>




This lecture's key point(s):


Courseware | Lecture notes

©Copyright Alan Dorin 2009