Appendix D. JavaScript code quality guide

 

This style guide aims to provide the ground rules for an application’s JavaScript code, so it’s highly readable and consistent across different developers on a team. The focus is put on quality and coherence across different pieces of your application.

D.1. Module organization

This style guide assumes you’re using a module system such as CommonJS,[1] AMD,[2] ES6 Modules,[3] or any other kind of module system. For a comprehensive introduction to module systems head over to chapter 5; I’ll wait.

1 The CommonJS module specification hosts a wiki page at http://bevacqua.io/bf/commonjs.

2 RequireJS has a comprehensive article on the purpose of AMD at http://bevacqua.io/bf/amd.

3 Getting started with ES6 is much easier these days! See http://bevacqua.io/bf/es6-intro.

Module systems provide individual scoping, avoid leaks to the global project, and improve code base organization by automating dependency graph generation, instead of having to resort to manually creating tens of <script> tags.

Module systems also provide Dependency Injection patterns, which are crucial when it comes to testing individual components in isolation.

D.1.1. Strict mode

Always put "use strict";[4] at the top of your modules. Strict mode allows you to catch nonsensical behavior, discourages poor practices, and is faster because it allows compilers to make certain assumptions about your code.

D.2. Strings

D.3. Conditionals

D.4. Regular expressions