Appendix A. JavaScript coding standard

 

This appendix covers:

  • Exploring why a coding standard is important
  • Laying out and documenting code consistently
  • Naming variables consistently
  • Isolating code using namespaces
  • Organizing files and ensuring consistent syntax
  • Validating code using JSLint
  • Using of a template that embodies the standard

Coding standards are contentious. Almost everyone agrees you should have one, but few seem to agree on what the standard should be. Let’s consider why a coding standard is especially important for JavaScript.

A.1. Why we need a coding standard

Having a well-defined standard for a loosely typed, dynamic language like JavaScript is almost certainly more important than with stricter languages. JavaScript’s very flexibility can make it a Pandora’s box of coding syntax and practice. Whereas stricter languages provide structure and consistency inherently, JavaScript requires discipline and an applied standard to achieve the same effect.

What follows is the standard we’ve used and revised over many years. It’s fairly comprehensive and cohesive, and we use it consistently throughout the book. Its presentation here isn’t very concise because we’ve added many explanations and examples. Most of it has been condensed into a three-page cheat-sheet found at https://github.com/mmikowski/spa.

A.2. Code layout and comments

A.3. Variable names

A.4. Variable declaration and assignment

A.5. Functions

A.6. Namespaces

A.7. File names and layout

A.8. Syntax

A.9. Validating code

A.10. A template for modules

A.11. Summary