Learning the syntax of a programming language is not an overly difficult process. The real challenge, however, is learning to use those basic building blocks to write complete, useful, clean and error-free code. Many eager programmers, when faced with a programming challenge, will sit down at the keyboard and start keying in code. The problem with this approach is that the code usually ends up being more complicated than necessary, and often the programmer will find that they've coded themselves into a hole that they have to dig their way out of. Although major problems are not likely to surface in smaller JavaScripts, large projects can easily suffer from poor preparation. The key to avoiding this problem is in good planning. One popular method of approaching problems is called the top-down approach to programming.
For this example, I am going to use a real-life task that I recently tackled using the top-down approach. This example was not written in JavaScript, but the concepts are the same for any language.
One of the most time-consuming aspects of this tutorial is doing the formatting for the examples that appear at the end of each section. After manually marking up the first two JavaScript articles, I decided to write a word macro to help. To begin working on the macro, I grabbed a pencil and a piece of paper. The first step in planning a program is to write down the major objective of the program:
That task alone is extremely daunting, and it's hard to know where to begin. The next step is to break down that task into smaller tasks:
With each step, the code becomes more manageable. For example, the second task can be broken down further:
At this time, each of those two separate tasks is manageable. The idea is to break down the main task into a tree of subtasks. You may have noticed that each of the smaller tasks becomes well suited for a function. Further, you will often find that many of the subtasks are the same, and one function will satisfy the needs of a number of the subtasks. For example, one of the subtasks below 'Create the source page' is to create hypertext links from each // Analysis string. Part of that task includes finding the beginning of // Analysis, much like finding the beginning of the </body> tag earlier.
Once you have dissected a major problem into all of its component tasks, the next step is to start building the program from the bottom up. Begin with the simplest function to implement and code it. The next step is to write a program that only tests that one function. Once the function is working correctly, you do the same for another function. From here, it is just a matter of assembling the pieces, and testing the program at every step. Before you know it, you've written a large and complex program from small and easily managed pieces. The examples at the end of this section include an entire project coded in the top-down method of programming, and it should clear up any remaining questions you may have.