Espen Hovlandsdal
Written by Espen Hovlandsdal
Published 2015-02-03

JavaScript Code Style

Code is read much more often than it is written. Having a consistent and defined coding style helps developers read the code, and it also helps to make a code base feel like one unit, instead of individual pieces written by different authors with their own way of doing things.

Having a coding standards is beneficial, but making people follow it is usually a bit harder. Let me introduce two awesome tools to help you: JSHint and JSCS.

Entry image

JSHint is a linting tool which helps you detect potential problems with your code. Things like detecting global variables, missing semicolons, invalid use of the typeof operator and unused/undefined variables. Paired with a plugin to your favorite editor, you’ll get a nice second fair of eyes on your code. You can also hook it up to run as part of your test suite, to ensure you don’t commit code that does not follow your standards. JSHint is configurable using a .jshintrc file in the root of your project folder – and there are a whole range of options to tweak it to your preferred style.

JSCS is another great tool. This one usually won’t uncover errors in your code like JSHint, but rather with the style of your code. It’s very easy to set up, yet it has a large set of rules to tweak it to the exact style you want to follow. These rules can be defined in a .jscsrc file in the root of your project folder, in the same was as JSHint (it also lets you put them in your package.json file if you prefer that). At VG, we picked a preset which matched our style the most and tweaked the few options that were not quite as we wanted it.

With these two tools in place, you can have fully automated validation of your javascript with very little effort. If you want to automatically run JSHint and JSCS as part of the testing process, simply put them in your package.json file as a pretest step:

Just be sure to add node_modules to your ignores for the respective tools, so you don’t end up linting third-party code ☺

Note: I recently wrote a long blog post about how to write, test and publish javascript modules. It also covered some quality assurance, such as running JSHint as part of the testing process.

Written by Espen Hovlandsdal
Published 2015-02-03