Team LiB
Previous Section Next Section

Coding Style

Because of the ease with which JavaScript can be used for a variety of tasks, developers often neglect good coding style in the rush to implement. Doing so often comes back to haunt them when later they are faced with mysterious bugs or code maintenance tasks and cannot easily decipher the meaning or intent of their own code. Practicing good coding habits can reduce such problems by bringing clarity and consistency to your scripts.

While we have emphasized what constitutes good coding style throughout the book, we summarize some of the key aspects in Table 23-6. We cannot stress enough how important good style is when undertaking a large development project, but even for smaller projects, good style can make a serious difference. The only (possible) time you might wish to take liberties with coding style is when compressing your scripts for speed, but then again you might want to let tools do that for you and write nice descriptive code for yourself.

Table 23-6: Good Coding Style Guidelines

Aspect of JavaScript


Variable identifiers

Use camel-back capitalization and descriptive names that give an indication of what value the variable might be expected to hold. Appropriate variable names are most often made up of one or more nouns.

Function identifiers

Use the camel-back capitalization and descriptive names that indicate what operation they carry out. Appropriate function names are most often made up of one or more verbs.

Variable declarations

Avoid implicitly declared variables as they clutter the global namespace and lead to confusion. Always use var to declare your variables in the most specific scope possible. Avoid global variables whenever possible.


Pass values that need to be modified by reference by wrapping them in a composite type. Or, alternatively, return the new value that the variable should take on. Avoid changing global variables from inside functions. Declare functions in the document <head> or in a linked .js library.


Indicate that object constructors are such by capitalizing the first letter of their identifier.


Use comments liberally. Complex conditionals should always be commented and so should functions.


Indent each block two to five spaces further than the enclosing block. Doing so gives visual cues as to nesting depth and the relationship between constructs like if/else.


Whenever possible, break your scripts up into externally linked libraries. Doing so facilitates code reuse and eases maintenance tasks.


Use them. Do not rely on implicit semicolon insertion.

Team LiB
Previous Section Next Section