• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

What's Your Function?

In the code shown in Listing 27.1, the write method is a common action. One of the purposes of a function is to simplify the code you write by making a common feature a single block of code that can be referenced numerous times. In this way, functions are similar to the SRC attribute for the <SCRIPT> tag discussed earlier. If there were no functions, you would have to key in that block of code at each point you wanted to use it, which would be a maintenance nightmare in the future if a particular piece of that common code were changed. Instead of updating it in one spot, you would have to manually find each occurrence of that code and update it.

Suppose you wanted to write an application that determined the number of notebook computers available for sale at an online computer store. If this number needed to be determined multiple times in a JavaScript application, it could be placed inside a function and invoked as needed. In this example, determining the number of computers available may require several lines of code behind the scenes: attaching to a database, retrieving information from a database, reformatting that information and returning it if no errors were encountered, and disconnecting from the database. As a Web page developer, you may want to be shielded from these actions. You especially do not want to include all these actions independently in your source code each time you want to determine the number of available laptops. It's more efficient to issue a single command such as GetNumberOfPCs.


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint