HTML Markup | JavaScript | Java | Home & Links

Tutorial 3 - Control Flow, Functions, Objects

This tutorial focuses on control flow structures, functions (ie. programming in the small) and objects. Topics include:

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. The round bracket contains initializer(s) ; conditional test ; incrementer(s). The test condition is checked prior to executing the block. Incrementing is done after executing the block. 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 the following loops through all the navigator object's properties while disregarding methods and functions.

msg="navigator object info:\n";
for (propname in navigator) if(typeof navigator[propname]==='string'){
  msg += propname + ": " + navigator[propname] + "\n";}
alert(msg);

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;}

Nested loops are possible. Be very careful about modifying any indices!.

int i,j;
for (i=0;i<10;i++) {
  for (j=i;j<10;j++) {document.write("*");}
  document.writeln();}

Switches

Switch (aka 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.

Continue, Break and Return

Continue statements are used in 'while' or 'for' statements to force another iteration of the loop. The following is a trivial example. Most often the continue is used as part of a conditional statement that only happens in certain cases.

x=0;
while (x<10) {
  x++;alert(x);continue;
  alert('you will never see this alert dialog');
  }

Break statements are used in 'while', 'for' and 'switch' statements to force an abrupt termination or exit from the loop. In the following example the loop is never completed. Once again the normal use of break is as part of a conditional statement.

x=0;
while (x<10) {
  x++;alert(x);break;
  alert('you will never see this alert dialog');
  }

Return statements are used to exit quickly from a function or to pass values back from the function.

Functions: Structure

Functions gather a group of statements together for performing a complex operation. The format of a function is:

function doIt(param1, param2, etc){
  some statement;
  another statement;
  etc;
  return xyz;
  }

A function's definition is begun with the keyword function followed by a unique identifier name and a set of round brackets. Inside the round brackets is a formal parameter list of identifiers or names for each value passed to the function, separated by commas. These values can be simple data (such as numbers or strings) or objects. The parameter list can also be empty (ie. null)! Statements within the function are grouped into a block using brace (curly) brackets.

A function is called or started by referring to it in another portion of the script or from an event handler. If used as a parameter, the keyword this refers to the current object.

Simple values are passed by value, ie. changing the formal parameter variable's value inside the function will not change the actual parameter's value outside the function. The arguments are considered as local variables.

Objects are passed by reference, ie modification inside the function will change the passed object. If this is not desired, make a copy of the object and then alter only the copy.

Functions can optionally return a single value back to the event handler or other function that called them. To alter more than one variable, either use global variables or pass objects (which can be altered).

Note: There is no semicolon after a curly bracket!

Note: Functions are NOT a part of object oriented programming but provide an much easier approach to fast program development. JavaScript makes the tradeoff of including functions to keep the language from being 'elitist' only!

Functions: An Example

Functions are useful when separating code from the XHTML (functions are normally found in head section) and can also be referenced or reused from several other points in the script.

function biggest(a,b,c){
  biggun=a; // assume first is biggest
  if(b>biggun){biggun=b;}
  if(c>biggun){biggun=c;}
  return biggun;
}
...
alert('biggest is '+biggest(x,y,z));

This function has three formal parameters. Based on the values fed in, the largest numerical is selected and returned to the calling function. The caller simply displays the result. Note that the actual parameter names in the calling function do not need to be (and in fact it is good programming practice that they are not) the same as the formal parameters used in the function.

Method Overloading

Method overloading is a form of polymorphism where the action of a method is determined by the number or type of parameters used. Although this object oriented principal is missing in JavaScript, actions based on a variant number of parameters can be faked.One way is to write the formal parameter list assuming the largest number of parameters expected and test each parameter name for presence.

function welcomeMessage(name){
  if (!name) {document.writeln('Welcome to my WebSite!');}
  else {document.writeln('Hello again, '+name);}
}

A second way is to use the internal array property arguments which returns all the arguments of the current function.

function smallest(){
  if (!arguments){'Operation is invalid!';}
  argc=arguments.length; argv=arguments;
  if (arc<1){'Operation is pointless!';}
  smallest=argv[0];
  for (i=1;i<argc;i++){
    if (argv[i]<smallest){smallest=argv[i];}
  } }

These two methods can be combined with only the mandatory parameters named and the ones with defaults checked using arguments. My cookie baking routine uses this mixed format.

Functions: Timing and Delays

JavaScript provides a setTimeOut(nextfn,millisec) method that will jump to nextfn after millisec of delay (it can be the same function as in adCycler). There are also times that you want to remain in the current function after the timeout. A simple delay function can be made from the internal clock:

function delay(millis){
date=new Date(); curDate=null;
do {curDate=new Date();} while (curDate-date<millis);
}

Functions: Recursion

Recursive functions are functions that are defined in terms of themselves. A classic recursion is factorials where n factorial is the product of positive integer n and all the products before it down to one. This could be programmed as:

function factorial(n){
  if (n==1) {return 1;}
  return n * factorial(n-1);
}

A recursive function must have some kind of terminator statement so that one finally escapes the loop.

Caution: This short function is not very well written as negative and floating calling parameters are illegal in factorials and will cause problems in terminating the loop. Bad input should always be trapped.

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 can 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 template

Objects 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



JR's HomePage | Comments [jstutor3.htm:2011 01 27]