Home > Articles

  • Print
  • + Share This
This chapter is from the book

Best Practices for JavaScript

You should now be familiar with the basic rules for writing valid JavaScript. Along with following the rules, it's also a good idea to follow best practices. The following practices may not be required, but you'll save yourself and others some headaches if you follow them.

  • Use comments liberally— These make your code easier for others to understand, and also easier for you to understand when you edit them later. They are also useful for marking the major divisions of a script.
  • Use a semicolon at the end of each statement, and only use one statement per line— This will make your scripts easier to debug.
  • Use separate JavaScript files whenever possible— This separates JavaScript from HTML and makes debugging easier, and also encourages you to write modular scripts that can be reused.
  • Avoid being browser-specific— As you learn more about JavaScript, you'll learn some features that only work in one browser. Avoid them unless absolutely necessary, and always test your code in more than one browser.
  • Keep JavaScript optional— Don't use JavaScript to perform an essential function on your site—for example, the primary navigation links. Whenever possible, users without JavaScript should be able to use your site, although it may not be quite as attractive or convenient. This strategy is known as progressive enhancement.

There are many more best practices involving more advanced aspects of JavaScript. These are covered in detail in Hour 15, "Unobtrusive Scripting."

  • + Share This
  • 🔖 Save To Your Account