JavaScript Functions

Function Libraries

As you write more and more JavaScript, you will find that there are a lot of common tasks that many of your scripts will need to perform. The easiest way to handle this repetitive code is to create your own collection of functions to perform those tasks. This collection of functions will form a 'library' that you can use to simplify each of those tasks into a single function call whenever needed in all of your future JavaScript projects. The amount of new code you need will be less for each new project because more and more of the processing required can be provided by the functions that you have already written.

If you look at the scripts I have written, you will see that there are a number of functions that are cmmon to many of them. These are functions that I have in my own function library which make it quicker and easier for me to write new JavaScripts.

Another advantage to using functions is that when someone else writes a function for you, you don't need to understand how the function works. As long as you know what the function does you can use it without worrying about how it works.

In addition to building your own function library, you can use those written by other people provided that you obtain the necessary permission to do so. There are many web sites that offer JavaScript functions for performing specific tasks that you to use provided that you acknowledge where you got them from. There are even a several rather huge JavaScript libraries available that are considered to be open source (so that anyone can use them). One of the big disadvantages of some of these huge JavaScript libraries is that they may or may not have adequate documentation. Where documentation is lacking, you cannot easily determine what functions that the library contains and what those functions do. Also, these libraries may be so large that they are the equivalent of several web pages in size all by themselves. In this case you may want to pick and choose which functions that you actually include in your web page. If the functions in the library are too interdependent, then by the time that you determine how to extract just those parts you need, you will have sufficient JavaScript knowledge it would be quicker to write your own.

What We Have Learnt

In this tutorial series we looked at how to separate out code into a function and call that function instead of having the code appear in multiple places in our page. This allows us to write the code to perform a particular process once and use it from as many places as we need to without duplicating the code. When we need to change that code there will only one place that needs to be changed in order for that same change to apply everywhere that the function is called.

go to previous section 


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow