Jan 30, 2009

Control Flow and Functions in Scripting

This tutorial focuses on control flow structures and functions. (ie. programming in the small) and includes the following topics:

Conditional Statements
Conditional statements execute a set of other statements only if certain conditions are met. The condition is always enclosed in round brackets. The statements to be performed if the condition is true are enclosed in blocks (ie curly brackets). For example:if (value > 5) { x = 7;}
Occasionally you may want to perform some actions for the false outcome of the condition as well. The else keyword is used to separate branches.if (name == "fred") { x = 4;} else { x = 20;}
NOTE: When the conditional if statement is used only to make an assignment to one variable, you can use the terse C syntax such as:x = (name == "fred") ? 4 : 20;

Loops and Switches
For loops allow a set of statements to be repeated or looped through a fixed number of times. For example to output #1 #2 #3 etc. on separate rows you could write:for (i=1; i<=15; i++) { document.writeln("#"+i); } For-in loops allow looping through all the elements of an array or properties of an object. Unfortunately, it also loops through all object methods and functions as well. The body of every for-in statement should be wrapped in an if statement that does filtering. The filter can select for a particular type or range of values, or it can exclude functions. For example:msg = "navigator object info:\n"; for (propname in navigator) if(typeof navigator[propname]==='string'){ msg += propname + ": " + navigator[propname] + "\n"; } alert(msg); would loop through all the navigator object's properties while disregarding methods and functions. While loops allow a set of statements to be repeated or looped through until a certain condition is met. For example to output #1 #2 #3 etc. on separate rows you could write:i = 1; while (i<=5) { document.writeln("#"+i); i = i + 1; } Switch (or case) statements are used to select which statements are to be executed depending on a variable's value matching a label.yourchoice=window.prompt('pick a number between 1 and 3'); switch (yourchoice) { case '1': alert('you typed a 1'); break; case '2': alert('you typed a 2'); break; case '3': alert('you typed a 3'); break; default: alert('Only 1, 2 or 3 allowed!'); } A problem with this example is that there is only one type of error checking done. What if the user had entered a punctuation sign or typed TWO instead. Also this is a forced example as one could have used the variable yourchoice within the alert method and not used a switch statement at all. Think of the example as just a demonstration of how the switch statement is structured.

Control Flow and Functions in Scripting

This tutorial focuses on control flow structures and functions. (ie. programming in the small) and includes the following topics:

Conditional Statements
Conditional statements execute a set of other statements only if certain conditions are met. The condition is always enclosed in round brackets. The statements to be performed if the condition is true are enclosed in blocks (ie curly brackets). For example:if (value > 5) { x = 7;}
Occasionally you may want to perform some actions for the false outcome of the condition as well. The else keyword is used to separate branches.if (name == "fred") { x = 4;} else { x = 20;}
NOTE: When the conditional if statement is used only to make an assignment to one variable, you can use the terse C syntax such as:x = (name == "fred") ? 4 : 20;

Loops and Switches
For loops allow a set of statements to be repeated or looped through a fixed number of times. For example to output #1 #2 #3 etc. on separate rows you could write:for (i=1; i<=15; i++) { document.writeln("#"+i); } For-in loops allow looping through all the elements of an array or properties of an object. Unfortunately, it also loops through all object methods and functions as well. The body of every for-in statement should be wrapped in an if statement that does filtering. The filter can select for a particular type or range of values, or it can exclude functions. For example:msg = "navigator object info:\n"; for (propname in navigator) if(typeof navigator[propname]==='string'){ msg += propname + ": " + navigator[propname] + "\n"; } alert(msg); would loop through all the navigator object's properties while disregarding methods and functions. While loops allow a set of statements to be repeated or looped through until a certain condition is met. For example to output #1 #2 #3 etc. on separate rows you could write:i = 1; while (i<=5) { document.writeln("#"+i); i = i + 1; } Switch (or case) statements are used to select which statements are to be executed depending on a variable's value matching a label.yourchoice=window.prompt('pick a number between 1 and 3'); switch (yourchoice) { case '1': alert('you typed a 1'); break; case '2': alert('you typed a 2'); break; case '3': alert('you typed a 3'); break; default: alert('Only 1, 2 or 3 allowed!'); } A problem with this example is that there is only one type of error checking done. What if the user had entered a punctuation sign or typed TWO instead. Also this is a forced example as one could have used the variable yourchoice within the alert method and not used a switch statement at all. Think of the example as just a demonstration of how the switch statement is structured.

Syntax and Grammar in Scripting

JavaScript like many languages (eg C, Java, awk, perl) is based on a common syntax and grammar developed by the Bell Labs in the 60's. This makes it easy to cross over from one language to another based on program requirements, resources and politics. This tutorial on JavaScript syntax and grammar (ie. programming in the small) assumes introductory programming experience in another language and includes the following topics:

Lexical Structure
The lexical structure of a programming language is the set of elementary rules that define what are the tokens or basic atoms of the program. It is the lowest level syntax of a language and specifies what is punctuation, reserved words, identifiers, constants and operators. Some of the basic rules for JavaScript are:
JavaScript is case sensitive.
Whitespace, tabs, and newline characters are ignored except when part of string constants. They can be added as needed for readability.
Single line comments begin with //
Multiline comments begin with /* and end with */
Statements terminate in semicolons! Make sure to always terminate statements with a semicolon.
Commas are used to separate words in a list
Round brackets are used for operator precedence and argument lists.
Square brackets are used for arrays and square bracket notation.
Curly or brace brackets are used for blocks.
Keywords are reserved words that have special meanings within the language syntax.
Identifiers are names for constants, variables, functions, loop labels, objects and classes. The first character must be an ASCII letter, underscore or dollar sign. Following characters can also include digits. JavaScript style begin class identifiers with a capital letter, uppercase constant ids and lowercase variables.Note: An identifier must NOT be any word on the JavaScript Reserved Word List.


Literal Constants
Literal constants are values that do not change within a program. Some types of literal constants are:
Boolean: true, false
Numeric 5, 2.543, 8e12, -4.1E-6, 073 [leading zero] (octal), 0xFF (hexadecimal)
String: 'fred', "Fred and Ethel"
Primitive: Infinity, NaN, null, undefined
Warning: Do not use leading zeros to format integers as this may give an unintended octal meaning. Use spaces instead!
Note: Floating point numbers less than one should begin with a leading zero. For example write 0.1 rather than .1
Warning: If a number begins with two zeros and contains a decimal point (eg. 005.3) it will generate an error. Validation techniques to guard against this type of error will be discussed in Getting the Bugs Out.
One question that is often asked is 'WHY can one use either kind of quote marks (they must match however) when defining a STRING value?'. Occasionally there is a need to have a string that uses an internal quote or possessive form or contraction (apostrophe). To handle one of these situations, bracket the string with the opposite form of quote.


Basic Display and Objects in Scripting

Basic Display and Objects
This series of JavaScript tutorials will help you to add interactivity to your XHTML documents. JavaScript uses modern object oriented programming techniques to make it easier to program and reuse code. The tutorials assume a working knowledge of XHTML and CSS and a commitment to validate all code including stylesheets.
In the JavaScript tutorials, text that is displayed in a blue box can be cut and pasted (aka ripped) into a new XHTML document template (ie. complete with doctype, head, title and body elements). You may prefer to type in the example yourself just so that you can review your understanding of each line as it is entered. Choose a strategy which works for you and have some fun learning about the power that JavaScript gives to web page designers.
Script code for working examples can be found in jscode.js. Download the file or cut/paste what you need.
Javascript code should always be written to the ECMA - Edition 3 standard. One of the best ways of checking your work is to use jsLint. Just cut and paste your script into the input box and press the jsLint button. Either you will get an 'ok' message or an easy to interpret message including line number on any problem. Code that checks out ok with jsLint will be less likely to be quirky in any of the modern browsers.

JavaScript Template
Several lines are always needed to separate your JavaScript code from the html markup in your document. To make coding easier make a template file or create a macro in your text editor that contains the following:
The first line creates an XHTML element which tells your browser that what follows is in a scripted language and should be interpreted using JavaScript. The next line starting with CDATA marks it as character data not to be interpreted by the browser. Otherwise characters like & and <>) respectively. JavaScript programs normally use <>".
Note: It is recommended that you write code that assumes that some users may not have JavaScript enabled browsers or have temporarily turned it off. This is part of the 'Be kind to ALL users' philosophy. XHTML provides an element specifically for this purpose. Make a template (or macro) of the following so that it can be included easily in the body section of every document that has a script element.
The message between will appear on a non-script enabled browser or one with scripting turned off. The noscript element must be placed in the body section of your document to be valid XHTML!.
Warning: Unfortunately modern browsers such as FireFox, Opera and SlimBrowser do not display the contents of a noscript element when JavaScript has been deselected. Use CSS style visibility to solve this issue.

JavaScript Placement
JavaScript is placed in one of four locations depending on how often the code is needed.
Short examples or trivial snippets can be placed inline (sometimes called on-the-fly). These are inserted (with the above template) into the body section of a document. Most JavaScript utilities are placed in the head section of a document. This assures that they are loaded immediately and that if appropriate can be used in several places in the document. JavaScript routines can also be isolated to separate files for reuse by several documents. Isolation also prevents XHTML validators from signaling false errors inside javascript. My tutorials use this method. JavaScript can be placed within element attributes by using the javascript: keyword. The best choice is to first develop and 'debug' scripts within the head element. This saves time switching between files. When the script is working well, then cut and paste it to a separate external file for reuse. To link to the external file, the script element changes to include a 'src' attribute but no content between the tags. For example:
NOTE: It is a long standing tradition for these external files to use the extension .js but it is not a requirement.

Example: 'Hello World!'
A common first programming assignment in many languages is to write the greeting 'hello world' to the screen. This will give you the chance to become familiar with your text editor and the development process as well as some basic JavaScript syntax.
document.writeln('hello world!'); may seem trivial but it has many points of interest that should be thoroughly understood. The word document indicates one of the system objects available in JavaScript. The complete list of built-in system objects is given in the Appendices. In this example document is used to direct data into an HTML document for display. The following dot indicates that a method or operation is to be applied to that particular object. In this example the method is writeln(). Brackets indicate a parameter or value to be used by the method. Inside the bracket is a quoted string value to be used as is. Matching double quotes may also be used but there are many situations where double quotes conflict with HTML attribute assignment so single quotes are preferred. Finally, the sentence known in programming as a statement) ends with a semicolon. There is another method called write() which is almost the same as writeln() but does not display a new line after the parameter value. New lines can be forced in JavaScript with the \n newline escape sequence.
Note: The CDATA construct is omitted from the short demos on this page as < and & are not used yet. But it could be and perhaps should be used consistently.

Alert, Prompt and Confirm Windows
JavaScript has three very simple ways of providing the user with information and possibly feedback through the use of popup windows. window.alert() is a window object method which displays a message but no feedback can be gathered from the user. There is only one string parameter.
The method window.prompt() displays a standard dialog which allows the user to enter data. Note that there are two strings, separated by commas as parameters. The first parameter is a prompt message. The second parameter sets the default value of the entry. It is normally blank but is required to give a blank input line in the MSIE browser.
The method window.confirm() displays a standard dialog which allows the user to respond with either ok or no. The parameter is a prompt message.
Example: Interactive 'Hello World!'To improve a bit on the basic 'hello world' example and to show how JavaScript can introduce interactivity with the user, let's prompt for the user's name and then use it in our display.
name=""; introduces the concept of a variable which is a temporary data holder. Variable names must begin with a letter, contain only alphanumeric characters and underscore, and are case sensitive. Reserved Words list words with special meanings that cannot be used as variable names. The Core Language tutorial has more details on variables, operators and statements.
After the data is entered using the prompt method, it is stored in the variable called name. It is then appended to the message 'hello ' and displayed on the screen. Note that an alert window could also have been used for the display.

Examples: Last Update and Current DateThis

snippet demonstrates a useful script to tag your web pages with the lastmodified property of the document object. Many authors hard code the file date into the text but forget to update it when the page changes. Why not let the browser do the work for you?
The next example introduces the system object called Date. A copy of the object called todaysDate is created using the new operator and then printed.


Objects, Properties and Methods
Objects are collections of related properties and methods. Properties are things, similar to variables but their contents are contained within the object itself. Methods are actions that can be performed on an object. Often methods alter one or more of an object's properties.
Note: An analogy may be of help here. One can consider cars as objects. They have a collection of properties, one of which is the status of the parking brakes (park_brake) (either set or released). One method or action would be to apply the parking brakes (apply_park_brake()) which would change the status of park_brake to set.
Object instances can be created when necessary by using the new operator keyword and equating them to a name. The created object can then have its properties accessed and appropriate methods applied to it. An example of object creation using our analogy would be:
myCar = new Car;// creates one car from the Car templateObjects are organized in a a hierarchy (or tree) structure. Their properties and methods can be accessed using either dot notation or square bracket notation. Although dot notation is most common, square bracket notation has the advantage that the strings could be replaced by string variables or built dynamically!
dot notation square bracket notation objectName.objectProperty objectName["objectProperty"] objectName.objectMethod() objectName["objectMethod()"] formName.controlName.value formName["controlName"]["value"]
A simple example using dot notation to access the math object's property PI reveals JavaScript's value of π.
window.alert('The value of PI is '+Math.PI);Another simple math example demonstrates a method that rounds a number to the closest integer.
window.alert('The value is '+Math.round(4.56789));There are many built-in core and client side browser specific objects with methods or routines to handle data gathering and display, string and math manipulation, and system calls. The object properties are used to retain settings for recall. And programmers can make their own object classes as shown in the advanced topic of user defined objects