Home

ABCs of Programming Constructs

Action Containers

While variables are containers for data, FUNCTIONS are CONTAINERS for ACTIONS (calculation or concatenation) or to perform a specific task (or series of tasks or calculations).  Like variables, functions are usually created at the top of the code for easy access. Functions are typically used to encapsulate the business logic. A function is called a procedure or subroutine in some programming languages. When you have to repeat code or whenever the code is similar, you should simplify that code by creating a function and then invoking that function anywhere in the code instead of having it written in several places. Functions are at their best when they are made “generic.” 

A. Functions

Like the reserved keyword var for a variable with a descriptive name, a function is declared using the reserved keyword function, follow by:

  • a descriptive name (usually a verbNoun) typically using camel case like getEmployee or getTotal that depicts an action or a calculation.
    TIP: Like variables, functions use the same naming convention.
  • a set of parenthesis [ ( ) ] with or without parameters (discussed later)
  • a set of curly braces [ {  } ] where a block of “action” code is placed

Also, like a variable that is created and stored in memory and then can be used, ascertain or reference later, so is the case with a function. Once a function is created and stored in memory, it can then be used by invoking (or calling) the function later.

FUNCTION THAT PERFORMS A TASK

When a function PERFORM A TASK (NOT A CALCULATION) its result can be seen based on the task it is told to do.

If you write code by itself, it will be executed IMMEDIATELY (e.g., when the page loads).

alert("Hello, World);

However, when you want to SUPPRESS (prevent) code from executing, you can wrap it in a function statement:

function helloWorld()
 {  
   alert("Hello, World");
 }

INVOKING A FUNCTION

However, unlike normal lines of code, code inside of a function is NOT executed immediately. Instead, it is placed in memory where it can be called (technical term is invoked) upon demand LATER using various means.  The most common way to invoke a function is to "call" it by its name with parentheses:

helloWorld(); // Returns "Hello, World" in an alert dialog box

FUNCTIONS THAT RETURN A RESULT

Beside just executing a PRE-DEFINED block of code (e.g., alert ("Hello, World");) to perform a task, a function can also return a RESULT of a CALCULATION. The keyword return followed by the value must be used, as the name implied, to return a SINGLE value that can be any data type (variable, result of another function, etc.) In this way, a function can be thought of as a VALUE for data types like a variable or an array talked about earlier. (e.g., var total = addNumbers(10,15)).

The return value is "returned" back to the place it was called.

function addNumbers(num1, num2)
 {
  var  firstNumber = num1;
  var secondNumber = num2;
  var total = firstNumber + secondNumber;
  return total;
 }
var totalSum = addNumbers(12,13); // Function will be return back HERE.
alert(totalSum); 

The above variable is set to the result of the function as its value: var totalSum = 25; Hence, function can be used as a value for a variable.

IMPORTANT NOTE: When a function RETURNS A RESULT OF A CALCULATION, its result cannot be seen unless you assign it to a variable and than display it through another object (e.g., text field, alert dialog box, etc.). This is akin to the human memory. When information is "stored" in a person memory, it is invisible to everyone else because it is in that person mind (or thought). To "see" that person's thought, the "data" could be written, so that it can be "seen" by many people or could be spoken so that is can be "heard" by many people.

Events are specialized functions. They are triggers for objects to do something.

There are other ways to invoke a function. How and where a function is called depends on its purpose and will be executed on the line where it is invoked except for events (See Events):
  1. Assign it to a variable  (e.g., var myVar = myFunction();)
  2. Invoke it within another function (See examples later)
  3. Have an event invoke it (See Events)

The major purpose of creating a function is to create a reusable block of code that perform a specific task (processing instructions) or calculation (return a value or a string) when needed so that it can be used in multiple places in the code. Most programmaing languages includes several built-in functions called methods (e.g., alert(), Number ()) that perform common tasks or calculations and can be access from anywhere in the code (See Methods).

Methods are functions. However, they are functions attached to objects. Methods are what objects can DO (e.g., hop, skip, and jump) or what can be done to them.

Even though method is a function, it doesn't use the key word function when used in a class.

TIP: Anytime you find yourself writing a similar piece of code, you should think about creating a function. Having duplicate code has several disadvantage:

  1. It is harder to read because there is more code
  2. It is harder to update because changes need to be made in multiple places in the code
  3. It is easier to make mistakes because you have to edit code in several places

GENERIC VS SPECIFIC FUNCTIONS

Some functions may have data passed to them inside of the parenthesis called parameters. These parameters can be used by the function to perform the task it needs to do. If a function does not have pass parameters, it is a generic function and will execute the same every time. Parameters are separated by commas. Parameters can be passed to either side of an assignment inside the function.

function addNumbers() 
 { 
   var num1 = 10;  
   var num2 = 5; 
   var total = num1 + num2;    
   alert(total);
 }
 addNumbers();  // Returns 15

The problem with the generic function above is that it will ALWAYS return 15 when it is invoked. To make the function more useful, you can make it more SPECIFIC by allowing it to pass parameters INTO the function that can be used BY the function.

function addNumbers(num1, num2)
 {
  var  firstNumber = num1; 
  var secondNumber = num2 ;
  var total = firstNumber + secondNumber;
  alert(total);
 }
 addNumbers(12, 13);  // Returns 25

Notice the two parameters (num1, num2) has been added to the generic function to make it more specific. Also, note that when the function is invoked (e.g., addNumbers(12, 13);), it is passed two arguments (12, 13) of any values to be used by the function.  While the values are called parameters in the function, it is called agruments when passed into the invocation of the function.  The order of the function arguments MUST be in the SAME order as the parameters in the function itself. Also, notice that parameters of a function become parts of variables in a function (e.g., var firstNumber = num1;).

It is helpful to think of this type of function as a recipe maker. Think of parameters as ingredients for the function.

You can also make an argument of a function OPTIONAL:

In JavaScript (ECMAScript 6 Draft), you can declare a default agrument value INSIDE the function declaration. Syntax is as follow:

function myFunction (requiredArgument, optionalArgument="defaultValue")
 { 
   // Code goes here....
 };        

Example of using a default value:

function totalCost (cost, taxRate=1.05)
 {
   var price = cost * taxRate;  return price;
 } 
 
var myPrice1 = totalCost(100, 1.10);
alert ("$" + myPrice1); // Returns $110....

var myPrice2 = totalCost(100, 1.05);
alert("$" +myPrice2); // Returns $105
IMPORTANT NOTE: The code may give you an error in Dreamweaver but will display in Firefox.

FUNCTIONS THAT RETURNS MULTIPLE VALUES

To return MULTIPLE values from a function, create an object or an array to store all of its values and then pass a SINGLE object to the function to get its MULTIPLE values:

var person = {firstName: "Bob" , lastName: "Jones"};
function getPersonInfo (personBio)
 {
  alert(personBio.firstName);
  alert(personBio.lastName);
 }
getPersonInfo(person);

NOTE: Notice in this example, the argument name (e.g., person) is different from the parameter name (personBio).

FUNCTIONS THAT RETURN A NUMBER

Here are some classical examples:

function getCircumference(diameter)
 {
  var circumference = Math.PI * diameter;
  return circumference   
  // Or, simply one line: return Math.PI * diameter;
 }
alert(getCircumference(5)); // Returns 15.707963267948966

Here is another example:

function celciusToFarenheit(temperature)
 {
  return (9/5) * (temperature + 32);
 }
alert(celciusToFarenheit(20)); // Returns 93.6
          
function farenheitToCelcius(temperature)
 {
  return (5/9) * (temperature - 32);
  }
alert(farenheitToCelcius(212)); // Returns 100

FUNCTION THAT RETURNS A STRING

function sendMessage (msg)
 {
  return  "Hello, " + msg;
 }
alert(sendMessage ("Bob")); // Returns "Hello, Bob"
alert(sendMessage("Mary")); // Returns "Hello, Mary"

FUNCTIONS IN A FUNCTION

NOTE: Typically, a function should only do a SINGLE task. When a function performs MULTIPLE tasks within a  SINGLE code block, it becomes difficult to reuse and manage. So instead of having the function do multiple tasks in a single code block, create a series of functions inside of the function as separate tasks. Below is pseudo code that demonstrates this concept:

function bakeCake(flour, milk, sugar, butter, egg, vanilla, temperature, servingSize)
 {
   Mix(white flour, whole milk, white sugar, butter, egg, vanilla)
   Bake(350)
   Serve(8)
  }

Notice that functions can be included and called from WITHIN another function.  In the example above, the functions Mix, Bake, and Serve are inside of the function bakeCake.  This is useful because it makes the function:

  • Smaller
  • Easier to read
  • More modular by separating steps into individual TASK
  • Automatic invocation of those functions

NOTE: Those functions (e.g., Mix(), Bake(), and Serve()); however, still need to be created OUTSIDE of the main function (bakeCake).

NOTE: Another analogy that can be used for the function is to think of it as a TO DO LIST with a series of tasks:

function buildHouse (concrete, wood, drywall, pipe, wiring ...)
 {
  LayPipes(pipe) 
  CreateFoundation (concrete)
  CreateFrame(wood)
  AddWiring(wire)
  CreateWall(drywall)
    ....
 } 

MAKING FUNCTIONS MODULAR

A function can read and write variables from outside the function. However, it is best practice to "pass" data into the function via arguments. This makes the function modular which means that it can be cut and pasted into another page or app and still work. Parameters of a function become variables in a funciton. While arguments and parameters are often used interchangeably, technically speaking, PARAMETERS are part of the function (e.g., function functionName (parameter1, parameter2) {...} ) and ARGUMENTS are part of the function call (e.g., functionName(argument1, argument2) ).

USING AN ARRAY/OBJECT AS A FUNCTION PARAMETER

Creating a custom object or array to use as a single parameter of a function has several advantages:

  • The object or array can contain multiple properties or elements, respectively.
  • Multiple parameters encapsulated in the array/object can be passed into the function. Unlike regular parameters in which the number of parameters typically has to match the invocation function arguments. Passing an object or array, you can "sneak in" properties easily. 
  • The object's properties or the array's elements can be processed INSIDE the function.
  • The function is a lot easier to read and maintain.

Here are some examples of passing an array or an object to a function:

// Generic Object ----------------------------------------------------------------------
var myPerson = new Object();
myPerson.name = "Bob Jones";
myPerson.city = "Austin";
myPerson.state = "Texas";
function identifyPerson(myPerson)
 {
   alert(myPerson.name); // Returns "Bob Jones"
   alert(myPerson.city); // Returns "Austin"
   alert(myPerson.state); // Returns "Texas"
 }
identifyPerson(myPerson);
// Regular Array -----------------------------------------------------------------------
var myPersonArray = new Array();
myPersonArray[0] = "Bob Jones";
myPersonArray[1] = "Austin";
myPersonArray[2] = "Texas";
function identifyPersonArray(myPersonArray)
 {
  alert(myPersonArray[0]);  // Returns "Bob Jones"
  alert(myPersonArray[1]); // Returns "Austin"
  alert(myPersonArray[2]); // Returns "Texas"
 }
identifyPersonArray(myPersonArray);
// Literal  Array (similar to Object)  ----------------------------------------------------------
var myPersonAssocArray = {name:"Bob Jones", city:"Austin", state:"Texas"};
function identifyPersonAssocArray(myPersonArray)
 {
  alert(myPersonAssocArray.name);  // Returns "Bob Jones"
  alert(myPersonAssocArray.city);  // Returns "Austin"
  alert(myPersonAssocArray.state);  // Returns "Texas"
  // Alternative ---------------------------------------------------------------------------
  alert(myPersonAssocArray["name"]);  // Returns "Bob Jones"
  alert(myPersonAssocArray["city"]);  // Returns "Austin"
  alert(myPersonAssocArray["state"]); // Returns "Texas"
 }
identifyPersonAssocArray(myPersonAssocArray);

PASSING ARGUMENTS BY VALUE OR BY REFERENCE

Primitive values (e.g., String, Number, Boolean) are passed by VALUE into a function. When an argument is passed by value, the value is COPIED into a local variable for use within the function. The original value is unaffected and remains unchanged regardless of what happens within the function. This is akin to DUPLICATING a file where the original file remains unchanges where it is located.

var firstValue = 10;
var secondValue = "Hello, World";
passByValue(firstValue, secondValue); 
function passByValue (firstValue, secondValue)
  { 
   firstValue++;
   secondValue += " Goodbye, World";
   alert("First Value INSIDE Function: " + firstValue); // Returns 11
   alert("Second Value INSIDE Function: " + secondValue); // "Hello, World Goodbye, World"
  }
alert("First Value OUTSIDE  Function: " + firstValue); // Return 10
alert("Second Value OUTSIDE  Function: " + secondValue);  // Returns "Hello, World" 

Complex data types (e.g., Objects, Arrays) are passed by REFERENCE into a function. When an argument is passed by reference, the ACTUALLY object is passed instead of COPIED. When the function runs, the code in the function body will change the object that is passed outside of the function. This is akin to creating SHORTCUT to an original file.  If you open the shortcut and make changes, those changes will be reflected in the orginal file where it is LINKED to.

var myObject = {x:10, y:15};
passByReference (myObject); 
function passByReference (myObjectParameter)
 {
  myObjectParameter.x++;
  myObjectParameter.y++;
  alert(myObjectParameter.x); // Returns 11
  alert(myObjectParameter.y); // Returns 16
 }
alert(myObject.x); // Returns 11
alert(myObject.y); // Returns 16

Changes made to the parameters WITHIN the function affect the object properties OUTSIDE the function.

B. Methods

Methods are functions. However, they are functions attached to objects. Methods are what objects can DO (e.g., animate objects, show/hide objects) or what can be done to them. Methods can be distinguished from properties because they will always have parenthesis. Like functions, methods may also have parameters passed to them.

Unlike a function, a method is NOT invoked by a function call (e.g., myFunction()) but rather by the object ITSELF (e.g., myObject.myMethod()).

Most programming languages have a host of built-in methods that can be used any where in your code. Below are examples of some common methods used in JavaScript:

  1. alert()
  2. Number()
  3. String()
  4. typeof()

However, you can create custom methods by creating an object an including method inside of it.  For example, you typically define an object to have properties and one or more methods:

var person =
 {
// This object has three propeties and two methods firstName : "Bob", lastName : "Jones", age : 53, fullName : function() { return this.firstName + " " + this.lastName; }, talk : function() { return "Hello, class" } }; alert(person.fullName()); // Returns "Bob Jones" alert(person.age); // Returns 53 as a number alert(person.talk()); // Returns "Hello, class" as a string

CAUTION: If you forget to use parenthesis with the method (e.g., person.fullName()), you will get the literal function statement:

alert(person.fullName); // Returns function() {return this.firstName + " " + this.lastName;}

NOTES:

  • Unlike a regular function, a method has no name (what is called an annonymous function) because it is INVOKE AUTOMATICALLLY by the OBJECT itself instead of a FUNCTION CALL.
  • Even though person is a VARIABLE because it was assigned to (=) an OBJECT, it can be TREATED like an object by using the DOT SYNTAX (e.g., person.fullName() instead just person).
  • The properties were each placed on a single line so that you can see the explaination that will be explained below better. Normally, they would be written on a single line or several lines.

While both properties and methods are both ASSOCIATED with an object, properties are associated with the variables part of the object (in the example above, firstName, lastName and age) and the method (e.g, fullName(), talk()) is associated with the function part of the object. However, without attempting to confuse the matter, ALL of of them including fullName are in reality properties of that object because they are on the left side of the colons (:) which denotes properties and their corresponding values which is usually stated as name/value pairs.

C. Events

Because events are specialized functions like methods, they are discussed briefly here. For more detail information on events, see the menu Trigger Containers.

Events are triggers for the the code to do "something" WHEN an event occurs. Some of the most common events in JavaScript are:

  1. onclick() – WHEN an HTML element is clicked
  2. onload() – WHEN the page loads
  3. onmouseover() – WHEN the mouse moves over an HTML element
  4. onmouseout() – WHEN the mouse is moved out of an HTML element
  5. onchange() – WHEN a form element has been changed
  6. onkeydown() – WHEN a key is pressed
  7. onsubmit() – WHEN a form is submitted
  8. onfocus() – WHEN a user tab TO on click INSIDE of a form element
  9. onblur() –WHEN a user tab FROM on click AWAY of a form element
    NOTE: Notice that events in JavaScript start with the prefix "on" that indicateS it is an event and not a general function or method.

A simple event is added to HTML element as regular HTML attribute. For example, a common technique is to use the onclick event attribute in a button to trigger the code to do something. In the examples below, when the Click Me button is clicked, the alert dialog box appears with the message "Hello, World."

<button onclick="alert('Hello, World')">Click Me</button>

Besides writing the code DIRECTLY INSIDE the HTML element, a better approach is to create a function within a set of <script> tags and then call that function from within the button:

<script>
 function helloWorld()
 {
   alert("Hello, World");
 }
</script>
<body>
<button onclick="helloWorld()">Click Me</button>
</body>

You will see later a third and even better approah using the addEventListener method to associate (register) an event to an object to make the code more modular.

Key points to remember about functions:

  • If the function is returning a value or a concentation, the keyword return must be placed at the end of the function code block because no code will be executed after the return.
    EXCEPTION: If the return is within an if/else statement. (GIVE EXAMPLE).
  • To make a function more specific, allow it to pass parameters to it.
  • A function can have parameters passed to it. Parameters of a function become variables in a function.
  • A function will return a value in the exact location it was invoked.
  • A function can return any data type (e.g., String, Number, Boolean, Arrays, Objects, etc.).
  • Functions parameters can be literal values, variables, objects or arrays.
  • You can place functions inside of a function to simplify the code
  • When passing multiple arguments, you have to ensure that the ORDER of the values that you pass into the invocation function match the function parameter order.
  • Parameters and arguments are not the same. Parameters are like variables that are not declared (no "var") inside of a function definition (i.e, function myFunction (parameter1, parameter2)). They are also called parameters when used inside the function block.  Arguments on the other hand, are the actually values that get passed into the function when it is invoked (e.g., myFunction(myArgument1, myArgument2)). The two names are used to determine where the data is. Multiple parameters or arguments are separated by commas.
  • There is no limit to the number of arguments that you can pass to a function. However, if a lot of data is needed, it is best practice to pass a more complex object like an object or an array to the function instead. Since a function can only return one value, you can store a function result in an array and return the array as a single value.
  • A variable declared OUTSIDE a function will become a GLOBAL variable and can be accessed from inside and outside the function. A variable INSIDE of a function is a LOCAL variable to that function and will to be seen outside of that function. If you attempt to access a variable that is define in a function but are attempting to access it outside the function, you will get an error. It is helpful to think of variables outside of a function like long-term memory and variables inside a function like short-term memory.

 

< Previous Topic     Next Topic >