Friday, February 8, 2013

command-line JSLint

Finding syntax errors and so forth is not work for programmers, it's a job for our very fast but dumb slaves, the computers.  Here is how to harness their power for good, by showing possible bugs in our JavaScript programs.

install a command-line JavaScript interpreter, Rhino

sudo apt-get install rhino

install JavaScript checker

mkdir -p ~/src/jslint/
cd ~/src/jslint/
wget https://raw.github.com/douglascrockford/JSLint/master/jslint.js

create a little wrapper

mkdir -p ~/bin/
echo '#!/bin/bash' >> ~/bin/jslint

echo 'rhino -f ~/src/jslint/jslint.js $*' >> ~/bin/jslint

Add ~/bin/ to your PATH

Test the checker

$ echo 'alert(ding)' >>testme.js
$ jslint !$

jslint testme.js
js: uncaught JavaScript runtime exception: ReferenceError: "ding" is not defined.

It works! In our sample code, we call "alert(ding)" using an undefined variable.  The code should be "alert('ding')" -- a quoted string.


Writing Testable Frontend Javascript

It's said that a program without tests doesn't exist. Adding code often creates as many bugs as features.  Just now I found an excellent, concrete article that makes it much easier to test dynamic web pages like ours:

https://shanetomlinson.com/2013/testing-javascript-frontend-part-1-anti-patterns-and-fixes/