This document discusses various tools for static analysis of JavaScript code, including JSLint, JSHint, JSONLint, the Google Closure Compiler, and others. It provides examples of how to use each tool and configure options. Regular expressions are demonstrated for filtering output. The importance of tuning tools to the specific codebase is emphasized.
6. TheCaseForStaticAnalysis
Static analysis can reveal interesting places to start
reading in an unfamiliar code base.
It can also be used to locate areas of the code base
that may benefit from refactoring.
Additionally static analysis may highlight potential
sources of latent bugs.
7. “Errors”aren’tnecessarilybad.
Edsger Dijkstra famously said that tests can show the
presence of bugs, but never their absence.
Static analysis can tell you where to start reading, but
it can’t tell you where and when to stop reading and
take action.
The feedback from any of these tools is ultimately just
another data point. How to respond to that data is a
problem static analysis can’t solve ;-)
11. Checksfordetectableerrors
Find places where semicolon insertion might
produce unintended results
Detect unintentional declaration of global variables
Detect undeclared variables
Warn about potential unintended behavior from ==
Flag usages of eval()
13. JSLint
npm -g install jslint
jslint jquery.js
JSLint is Douglas Crockford's personal linting tool.
It ships with a great default ruleset -- Crockford's own,
constantly updated as he continues to learn about
JavaScript and its pitfalls.
JSLint is highly opinionated. While this is generally
seen as a good thing, there's a limited amount of
flexibility when it comes to disabling individual rules.
It’s hard to apply JSLint to legacy code.
14. JSHint
npm -g install jshint
jshint jquery.js
JSHint is very similar to JSLint (in fact it began life as
JSLint fork) but all of JSHint’s warnings and errors can
be configured or disabled via command line options or
with a .jshintrc configuration file.
15. JSONLint
npm -g install jsonlint
jsonlint myFile.json
JSONLint is a validator for the JSON data-interchange
format. JSON is used by almost all modern Web APIs.
JSONLint automates the process of testing whether
there are parsiing errors in a block of JSON.
16. GoogleClosureCompiler
curl -sO http://closure-compiler.googlecode.com/files/compiler-latest.zip
unzip -qo compiler-latest.zip
java -jar compiler.jar jquery.js
Closure compilation is the closest thing that JavaScript
has to an "interpreter" syntax check like php
-‐l or
ruby
-‐c
Closure also warns you about potential issues such
as missing parameters and undeclared or redefined
variables.
If code won't compile with the Closure Compiler, then
you can be certain said code is deeply hosed in some
fundamental way.
28. RegularExpressions
jslint jquery.js |
egrep -v 'is OK.$' |
egrep -v '^ *$'
This relatively simple regex suppresses status
messages from JSLint. The only lines that will be
printed are lines containing errors and warnings.