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

Recommendation

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.

Functions

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.

Constructors

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

Comments

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

Indentation

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 .

Modularization

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

Semicolons

Use them. Do not rely on implicit semicolon insertion.




JavaScript 2.0
JavaScript: The Complete Reference, Second Edition
ISBN: 0072253576
EAN: 2147483647
Year: 2004
Pages: 209

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net