Skip to content

Some Notes Towards Javascript Style

February 22, 2010

I’ve been informally adding to various parts of the company wiki where I work, and have created a small Javascript style guide. I’m reprinting it here (with the company-specific parts removed), in order to get some feedback. This was built for programmers with widely differing skill levels.

If you feel like commenting, if only to tell me I’m on drugs, please feel free. I’m looking for feedback regarding missing items, order of the rules, differing opinions, etc. Suggestions and links are welcome.

Javascript — Notes on Style

Javascript has evolved as a language, and it’s usage within web pages has evolved as well. The following are some general guidelines in regards to style and integrating Javascript into a project.

Use debugging tools.

Currently, Firefox is ahead of most other browsers in terms of standards-compliance, and has many exceptional debugging tools. It’s best to test against Firefox 3 first, and use Firebug as a debugger.

Avoid the use of inline event handlers in favor of Javascript functions that handle events for you.

Inline event handlers force you to change the HTML when you upgrade your Javascript, or switch to a different Javascript library to provide the same functionality. It is almost always better to declare your event handlers within your script itself.

Consider the use of Event delegation to improve the performance of your pages that have many event handlers.

Prefer the use of a standardized Javascript library over a home-brew list of utilities. Prefer the ones already integrated into your project over any other library.

There are many freely-available Javascript libraries from third-party sources. These are maintained by an active developer community, and have online resources for proper usage. These can be used to build the major pieces of functionality and utilities you will require, freeing you to code the custom pieces your project requires.

Do not use freely-available ‘snippets’ or ‘plug-ins’ if you can’t modify them yourself.

There is a lot of free code on the internet, many of which can solve an immediate issue. However, if you can’t read the code without fully understanding it, your ability to safely modify it when requirements change is very low. The introduction of bugs isn’t worth the initial time savings. Only use code you can clearly understand.

Avoid the use of eval.

The Javascript function eval contains numerous security holes and is memory-intensive.

Avoid the use of regular expressions (when possible).

Although regular expressions provide tremendous flexibility in pattern matching, they are also one of the most memory-intensive parts of Javascript. Your script will almost always run faster using the conventional string-matching functions.

Avoid global variables.

It is almost always better to encapsulate variables within a function or component than it is to declare it globally. A global variable can be changed by any other script included on the page, leading to subtle bugs that are difficult to identify and harder to correct.

DRY (Don’t Repeat Yourself)

If you find yourself duplicating code, remove the code from both locations and create a function to encapsulate that functionality. When two separate Javascript files contain the same function, remove it from both files and create a utility library for that section of the website. Repeat until all duplication is removed. This will keep the amount of files to a minimum, and make the code more compact and easier to maintain.

Naming Conventions

Naming conventions allow code to be passed between developers and understood clearly. They create a ‘house style’ that developers will pick up and use to more rapidly read and comprehend your code and reduce the chances that it will be misunderstood.

  • Use standard camelCase for variable and function declarations. Use UPPERCASE to name module and constants. Use CamelCase with the first letter capitalized for sub-components. Pluralize array names.
  • Never reduce a word to an abbreviation (i.e. use message instead of msg); this will make your code less readable (by both yourself and others).
  • Prefer verbs for functions [writeToFile(), getJSON()], and nouns for modules and variables.
  • Decide on a set of standard qualifiers for functions that do the same thing. For instance, for functions that check for boolean conditions, you could use ‘is’ as a qualifier [isXML(), isValid(), isAvailable()]. Java uses is, get, and set as standard qualifiers (is to check for boolean conditions, get to retrieve variables, and set to change variables).
  • Use a standard set of names for temporary variables (i, j, k for loop counters, x and y for dimensions, etc).

Prefer CSS to Javascript whenever possible.

CSS rollovers, rounded corners, image replacement and image sprite techniques require less memory overhead from a browser, generally use less code, and are more robust. Use these techniques whenever possible to reduce the amount of Javascript required on projects.

They call it the bleeding edge because it makes you bleed.

Prefer to use parts of the language that are well-understood, widely implemented, and bug-free. You will spend less time debugging, and your code will stand up to changes in browser usage patterns.

Prefer object detection over browser detection.

If you are unsure a browser implements the part of Javascript you need, test for the presence of that object instead of the browser. Browser user-agent strings can be faked. Also, you can prevent that part of your code from executing if the object is not present, and provide graceful degradation for any user-agent that is incapable of using that object.

Prefer the DOM.

The DOM is complex, verbose, and hardly ideal, but it is the only cross-browser standard that is currently implemented. It allows you to work with multiple XML-based dialects (HTML, XHTML, RSS, Atom, etc) in a consistent, uniform manner.

On comments.

Comment your code to establish: its purpose, which part of the site it was built for, what dependencies exist, and what specific parts of your code are not immediately obvious. Commenting greatly alleviates the need to provide external documentation, and should be used to reduce that need whenever possible. Comments and code should be kept in sync. Review your comments after you’ve changed your code. Complex data structures (deep nesting of if statements, fall-through’s in switch statements, etc) should be commented in a way that makes it obvious where a statement begins and ends.

Test (and build) your pages in this order: HTML, CSS, and Javascript.

By building the page using nothing but HTML, you gain these benefits: standards-compliance (validating your markup) and semantic structure (using tags that describe the function of the text, not it’s visual layout). These benefits (almost always) automatically convey the following: SEO, accessibility, and portability. In many cases, your pages will both work and be legible with Javascript and CSS turned off.

With this in place, adding CSS to conform to the designer’s visual layout, and then adding Javascript to apply interactivity, will make the page easier to understand, maintain, and modify in the future.

In general, it will also reduce the amount of code you need to write. Carefully planning the HTML first also reduces the amount of class and id attributes on HTML elements. By keeping classes and id’s to a minimum, you can optimize event handler placement, make the CSS more portable, and generally save bandwidth and reduce file size.

Keep good reference.

Save functions you expect to reuse in a folder on your desktop. Buy books on Javascript. Go to respected web sites, forums, and blogs.

Revise.

Whenever possible, review and revise your code prior to release to production. The act of reviewing and revising allows you to streamline, rethink, and generally produce code that’s easier to reuse in different contexts. This additional labor saves time and energy later. It is generally harder to revise scripts that are in production, because other programmers maintaining different areas may depend on the functionality of your code remaining constant.

Advertisements
One Comment leave one →
  1. February 24, 2010 8:51 pm

    Nicely done sir.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: