1. Technology

The Purpose of Functions

By

When we are writing JavaScript to perform any significant amount of processing we will sometimes have the same group of statements appear multiple times. Functions allow us to remove these statements from all of the places that they are needed and define them just once. We then “call” the function from each of the places where we need those statements to run. This makes maintaining the code easier as we only have one place where the particular series of statements occurs rather than repetitions of the same code. Any changes to that one block will automatically apply to each place where the function is called.

Using functions also allows us to modularize our approach to writing the code. This means that we can break up the processing into sections and not concern ourselves with how all of the processing needs to work all at the same time. When we are coding the function we need only concern ourselves with how the function needs to be coded in order to perform its intended task. When we are writing the code that calls the function we don’t can assume that the function will perform that task without having to concern ourselves with how it does it We will look at a more advanced way of modularizing things still further later in the book when we discuss object.

When writing JavaScript using functions, there are two different ways that we can work. We can take a top down approach. This means that we write the main code including calls to functions first without considering the code that the functions will need. Once that part is finished, we then focus on what each of the functions needs to do and write the code for them one at a time.

The alternative is a bottom up approach. This is where you write the functions first and then link them together.

Except where you already have the functions written and are going to reuse them (another advantage of using functions), you will probably find that a top down approach is easier. You will have a better idea of what each function actually needs to do if you know where it will be used before you write it.

Different parts of your JavaScript may need to respond to different actions that are performed by the people visiting your web page. By dividing your code up into separate functions you can clearly identify which code is to run when particular actions are taken. The code that is not relevant to that action is skipped, because that function is not called.

  1. About.com
  2. Technology
  3. JavaScript

©2014 About.com. All rights reserved.