Last Modified: 11/9/98
[Previous] [Home] [Next]

Programming with JavaScript


Credit: J. Trauger (JPL/NASA)

Programming Style

In most cases, you should write programs which emphasize clarity of structure and ease of comprehension, as if you were writing to another person rather than to a machine. Since you often have to maintain and alter your own code, that "other person" will be you 6 months in the future. The points that I strive for include the following:
  • Careful delineation of the start and end of functions
  • Documentation of each significant variable
  • Sparse documentation within the body of a function (usually on the right side of expressions) so as not to interfere with understanding the flow of control
  • Formatting output (especially HTML and JavaScript output) so it closely corresponds with the actual appearance of the output
  • Alignment of expressions so that differences between similar expressions can easily be spotted
  • Using understandable code versus compact code.
  • Using upper/lower case effectively. I stick with the convention that Classes begin with an uppercase letter. Uppercase letters are used in the middle of variable names to emphasize components, e.g., "upperRight" and "upperLeft".
See this for examples of the above style guidelines.

Debugging JavaScript

There are two main aspects of debugging JavaScript that you need to know:
  • Almost all errors print out the line where the error was detected. You need some type of editor which prints out line numbers. One you can use is "view" which views a file but will not change it. The commands you need know are:
    -- view my.html
    -- :set number
    -- nn (that is, the actual line number, such as 127)
    -- :q! (to exit "view")
    You can also use the arrow keys to move around, and if you ever get in trouble, press the Esc-key twice and you should be OK. Click on this for an example of a typical JavaScript error message.
  • The other main point is that you need to write debugging files in either plain text or HTML. Examples of this appear below.

Examples

Here we have a large number of examples which illustrate the concepts introduced so far. Each example consists of its source code followed by its actual execution.

[Previous] [Home] [Next]