I’ve talked about SpiderMonkey before. Being able to instantly evaluate JavaScript code is great but you can use FireBug for that. I argued that the main reason to use SpiderMonkey is to script the command-line. Integrating with JSLint is an example of using your tools intelligently.
JSLint
JSLint is a tool that “looks for problems in JavaScript programs”. Here’s a list of things JSLint looks for (full list):
- missing semicolons
- missing curly braces ({})
- the use of with
- the unfiltered use of for in
- the use of eval
- the implicit use of global variables
- missing break statements
- double var definitions
- the appropriate use of = and == and ===
- unreachable code
JSLint is just a way to check your code. However, JSLint, as it stands, is a textarea on the web:
Every time you edit your code, do you want to go jslint.com, paste only the relevant portion of your code, fix the errors locally, rinse and repeat? Anything that causes friction won’t get done. Let’s minimize that.
With SpiderMonkey
As it turns out, JSLint is a JavaScript program that parses JavaScript (!). Knowing that you can evaluate JavaScript on the command-line with SpiderMonkey, you have all the ingredients you need to automate the process.
Most of the solution is here. Look for this button: (direct link)
I renamed the file to jslint.js and put it in ~/etc/bin. I then created a shell script to script the process:
filename=${1:?"jslint filename"}
js -f ~/etc/bin/jslint.js < $filename
I named it ~/etc/bin/jslint (chmod +x).
Stupid Example
Let’s take a stupid example: (stupid.js)
y = x
if(y == 0)
return 5
}
What’s wrong with this? Plenty:
After the fixes:
y = x;
if(y === 0) {
return 5;
}
}
JSLint is just one tool. Let’s run this code through SpiderMonkey’s strict mode:
And this is for a trivial 7-line function. Running JSLint on hundreds of lines of code can be sobering experience. There’s even a warning on the site:
Seriously. As you become better with JavaScript and regularly check your code against JSLint (as a formality, of course), there seems to be no end to how nitpicky JSLint can be.
Finally, you can configure what JSLint will complain about by putting a specially-formatted comment in your file:
function stupid(x) {
y = x;
if(y === 0) {
return 5;
}
}
The undef option will make JSLint complain about using the global variable y which definitely looks like a mistake.
The full list of options is available here.
Thank you for the post. Pre-Commit-Hook for JSLint in Git would be nice.
for js in $(git diff-index –name-only –cached HEAD — | grep ‘\.js$’); do
if jslint.sh $js 2>&1 | grep ‘Lint at line’ ; then
echo $js
exit 1
else
echo “js files validated”
exit 0
fi
done
[…] have talked before about JSLint in the context of SpiderMonkey, but, nowadays, I install node.js for a few things. If I run JSLint through node.js, that means I […]