Simplify your life with JShint

Detect some code problems using static analysis.

Setup jshint

introduction

Obvious: JavaScript is an interpreted language without compile step.

Which means there is no compiler to check if every variable is declared, or a function exists before calling it. This leads to broken code discovered in production.

Fortunately, a combination of static analysis plus unit tests solves the majority of problems that a typical compiler would find out.

jshint

jslint used to be the preferred tool for static JavaScript checking, due to its author Douglas Crockford being an early very influential author. Later it was forked into jshint. While jslint languished, the jshint is being actively developed.

Both tools can be easily setup using nodejs, but I prefer jshint myself:

npm install -g jshint

Run jshint static analysis on foo.js

jshint foo.js
// prints found style and code issues

configuration

There are multiple ways to configure jshint, the preferred way is to create a json configure file called .jshintrc. Here is a sample:

{
    "maxerr"        : 50,
    "bitwise"       : true,
    "camelcase"     : false,
    "curly"         : true,
    "eqeqeq"        : true,
    "forin"         : true,
    "immed"         : true,
    "indent"        : 4
}

You can see current list of all available options and their explanations.

Once you have configured the .jshintrc file at the root of the project, you can use it from the command line

jshint -c .jshintrc foo.js

You can also point other tools to use the same options, avoiding duplicate configuration among IDEs, command line and grunt plugin. For exact instructions see this extensive list.

If you need to temporarily change jshint options inside a file, you can use inline configuration. For example, to let jshint know that a particular global variable is available in this file only use:

/* global MY_LIB: false */

integration with grunt

gruntjs has contrib-jshint plugin that makes running jshint a part of the normal workflow. Typical configuration using external .jshintrc file:

jshint: {
  src: [
    '<%= app_files.js %>'
  ],
  test: [
    '<%= app_files.jsunit %>'
  ],
  options: {
    jshintrc: '.jshintrc'
  },
  globals: {}
}

starting with jshint

The best practices for starting using jshint in your project:

  • use common .jshintrc file
  • point your IDE / text editor at .jshintrc file using a plugin
  • start with few settings, for example indentation and environment and progressively tighten the settings
  • solve jshint issues as soon as they appear
  • make it a part of the precommit check

Related

There are other linters aside from jshint. Read this comparison article. If you use Gulp you can bring all linters into your project at once using gulp-lint-everything