Check Your JavaScript for Syntax Errors Outside the Browser

by Buddy Lindsey on December 19, 2011

Writing JavaScript can really suck when you have simple syntax errors. Often you have to refresh the page, in a browser, to make sure the code is syntactically correct. Working more with JavaScript, especially PhoneGap, making sure the syntax is correct before even bothering to run the JavaScript code is a must since it takes so long to actually run the code. And that doesn’t even include the fact a lot of interpreters just eat errors.

JavaScript Lint To the Rescue

JavaScript Lint uses the Firefox browsers JavaScript engine to check your syntax for errors or, if you want, common mistakes people make. It is very useful since you can run a command and poof it gives you all your errors, warnings and why it is wrong where.

Getting JavaScript Lint

Mac OS X

brew install jslint

More Universal

node-lint can be installed as well using the node package manager. For some reason npm is screwed up on my computer so this wasn’t an option for me.

Usage

To use JavaScript Lint you run the following command on a javascript file:

     jsl -process app.js

It will either show you errors and warnings or output:

0 errors, 0 warnings

Making Usage Easier

Typing that every time can be come tiresome so to make things easier I setup a little script and aliased it so running it on the command line is easier.

I created a file ~/.scripts/pjs.rb and added the following code:

#! /usr/bin/ruby
system("jsl -process #{ARGV[0]} -nologo -nofilelisting")

I also added the following to my ~/.bash_profile

alias pjs='~/.scripts/pjs.rb'

From there while on the command line I just do the following:

pjs app.js

And it works. Makes life a lot easier when running JavaScript Lint and I am more confident in my JavaScript code I write now, at least with regards to syntax. The next thing I am going to do is bind that command to one in vim to make things even quicker.

Some may ask why I took this approach, and the answer is simple. By running the command through another script all I have to do is edit the ruby script here and there. It leads to more future flexibility over just setting an alias to jsl directly. I have a few other ideas on things I can do in the future so I just started with the end in mind.

Related Posts:

Was this Helpful?

If you found this article useful you might find others useful as well. Please browse the archives and subscribe to the RSS Feed to stay up-to-date.

Leave a Comment

Previous post:

Next post: