Simple Function Example: Removing Duplication

One of the primary purposes of functions in JavaScript is to avoid unnecessary duplication in your scripts. Consider the following script (view source to see it):

The commands in parts one, two, and three are very similar. They differ only in the variable that is used. Rather than duplicating very similar sets of commands, it is better to put the duplicated material in a function. The part that is different (the variable in this case) will become a parameter to the function. Here's how you would do this to the above example:

Note that by doing this, we've eliminated the duplication. Also, note the use of v: it stands as a proxy for x, y, or z, depending upon how the function is called. We've created a new command we can use in our scripts, called someFacts.

As a final note, we might perhaps generalize our function further. It could take a second parameter representing the multiplicative factor. This condenses the script even more, while achieving the same effects. Also, we can arrange to call our new function inside a loop. Take a look: