CIS 89C  Client-Side Programming with JavaScript

 

Unit 6 - Functions and Libraries (week 3)

 

References:

 

McDuffie - Chapter 8 Functions and Libraries

 

Topics:

 

Opening statement

What is a function - McDuffie page 224

Types of functions - McDuffie page 224

The best programming practices - McDuffie page 225

Defining and calling functions - McDuffie page 225

Scope -  McDuffie page 233

 

 

***********************************************************

Opening statement

 

Functions are widely used.  We will look at some more about functions.

 

 

***********************************************************

What is a function

 

As in other programming languages, a function is a set of code that is written.

You can call the function, and the code will execute.

There may be arguments passed to the parameters of the function.

There may be a single return from the function.

 

A statement is an expression followed by a semicolon or the end of the line of code.  I suggest you end statements with both a semicolon and the end of the line.

 

 

***********************************************************

Types of functions

 

Four types of functions:

 

1. Predefined functions

 

They are specified as part of the JavaScript language.

They are provided, with the interpreter, by the user agent (browser).

 

2. Predefined methods

 

A method differs from a global function.

The difference is that a method belongs to an object.

There are a number of predefined objects, specified as part of JavaScript.

Many of these objects have functions.  For example:

The document object has a write method:

 

document.write("some string");

 

Also, some kinds of objects all have a predefined method.

For example, all Date objects have a getDate() method.

 

myDate.getDate()

 

3. User defined "global" functions

 

User defined global functions are actually methods of the window object.

The trick is that the window object does not need to be specified, but is implied when  you do not use any other object.  So they look like global functions.

But, sometimes it is important to remember that they are methods, that belong to the window object.

 

4. User defined methods

 

You can write methods for your objects.

You can also write additional methods for the objects supplied with JavaScript.

 

 

We will focus on 3. global functions in this unit.

 

 

***********************************************************

The best programming practices

 

1. A function should do only one task, and do it well.

 

2. It is best if a function only uses the data passed to it in parameters, and its internal data.  (We will see some functions, call-back functions, that have no parameters, and need to get data somehow.)

 

3. Create good documentation for your functions. Give them good names.  Give your variables good names.  Put a comment at the beginning of each function telling what the parameters carry, what the function does, and what it returns.

It is good to put an eye catcher at the beginning of each function; this is very helpful in a large program.  Comments at the beginning of a large program should tell how the functions work together, and what the overall organization is.

 

 

***********************************************************

Defining a function with no parameters

 

function myFunctionName()

  {

 

  }

 

1. start with the keyword function

2. name of the function

3. parentheses - nothing in them when no parameters are specified

4. opening and closing braces.  Indent 2 or 3 spaces; align them so you can see the matching opening and closing braces.  (Some people do not line them up, which makes it hard to find the matching braces.  The book does not align them.)

 

example:

 

function threeBlankLines()

  {

  document.write("<br /> <br /> <br />");

  }

 

Where to define your functions

 

The functions must be defined before they are called.

 

The best place to put them is in the head.

They do not actually do anything, until they are called.

The actual work is done in the body.

The head is before the body, so it is a good place to put the functions.

 

example:

 

<head>

  <title>Sample</title>

  <script type="text/javascript" src="myFunctionFile.js" />

  <link rel="stylesheet" type="text/css" href="myStyleSheet.css" />

</head>

 

Notice the difference in how a JavaScript file and a Cascading Style Sheet file are included.  Put your JavaScript functions in your function file.

 

Where to call your functions

 

It is important where you call your functions.

You must call functions that are defined in the same JavaScript file as the call, OR

The JavaScript file containing the functions must be included in the xhtml document before the JavaScript file containing the call.

You must call functions where you want the resulting xhtml elements or text to be placed.

So, you must call functions in the body.

 

example:

 

<body>

  Hello, then three blank lines

  <script type="text/javascript" src="myExectionFile.js" />

  then Goodbye

</body>

 

Suppose you put the threeBlankLines() function in myFunctionFile.js which is included in the head.

Suppose you’re myExecutionFile.js contains:

 

threeBlankLines();

 

When the head element is interpreted, the function is defined.

When the body element is interpreted, the function executes, and puts three carriage returns between Hello and Goodbye.

 

Defining functions with parameters

 

If you want to specify parameters, to receive arguments passed to them when the function is called, put the parameters in the parentheses when you define the function.

 

Example:

 

printNameReversed ( firstName, lastName)

  {

  document.write("The name in reverse order is: ");

  document.write(lastName + ", " + firstName);

  }

 

When you call the function, you may provide arguments, which will be used as the value of the parameters.

 

Example:

 

printNameReversed( "Tom", "Jones");

 

will print:

The name in reverse order is: Jones, Tom

 

printNameReversed( "Mary", "Schmidt" );

 

will print:

The name in reverse order is: Schmidt, Mary

 

Passing by value

 

Passing primitive data types as arguments is done by value.

 

The primitive data types are:

 

- number

- string

- Boolean

 

example:

 

In <head> provide a script containing:

 

function fixString(aString)

  {

  aString = "Goodbye"

  alert(aString);       // displays Goodbye

  }

 

In <body> provide a script containing:

 

var myString = "Hello";

fixString(myString);

alert(aString);         // displays Hello

 

aString is a parameter variable in the function fixString.

myString is a variable in the script in the <body>.

They are separate variables.

Only the value "Hello" is passed into aString when fixString() is called.

 

Passing by reference

 

Objects and arrays are passed by reference.

There is only one object or array.

The calling variable and the parameter variable both refer to the same Object or array.  This means any change made in the function will be seen in the calling variable too.  We will study objects and arrays later.

 

Returning something from a function

 

A function can return the value of one number, string, or Boolean value.

Alternately, a function can return a reference to one object or array.

Be careful not to return a reference to a local variable in the function,

because when the function returns the local variables that were in the function may be destroyed.  (They are destroyed sooner or later.)

 

Example:

 

function double(value)

  {

  return 2 * value;

  }

 

var result;

var start = 4;

result = double(start);

alert(result);          // displays 8

 

Best practice is to have only one return statement.

It should be the last statement in the function.

 

 

***********************************************************

Scope

 

Local scope

 

Variables and parameters, which are part of a function, are local to that function.

They are different variables than any variables outside the function.

They are used only within the function.

This is called local scope.

The scope is local to the function.

 

Example:

 

function stuff()

  {

  var x = 3;

  alert(x);   // displays 3

  }

 

var x = 5;

stuff();

alert(x); // displays 5

 

Global scope

 

In most programming languages, variables defined outside functions have global scope.

JavaScript is a little different.

These, so called, "global" variables, defined outside functions" are global to the window object.

If you change to a different object, such as a different window, these variables are out of scope, and cannot be directly accessed.

We will look at sharing variables from a different window, later.

 

Current object

 

This brings up an important point that lurks in the background:

There is a scope for a variable, which may be local to a function, or global to the object (usually a window object).

 

There is also a current object.  Unless you change it, the current object is the window object.  It can get a little complicated when the global scope changes, because you have changed the current object.  We may see a little of this later.

 

***********************************************************

Summary

 

We have looked primarily at user defined functions,

that are "global" to the window object.

 

You put the functions in a script specified in the <head> element.

You use functions in scripts specified in the <body> element.

Where you use the function is where you are building text or elements within the <body> of the xhtml document.

 

Primitive data types are passed by value.

Arrays and objects are passed by reference.