Best practices & JSLint

JSLint” is a JavaScript “code quality tool”. If you’ve never heard of it then think of it as the W3C HTML validator, but for JavaScript. Doug Crockford, the genius that created JSLint, frequently claims that JavaScript is “The World’s Most Misunderstood Programming Language”; if you want to know where he’s coming from with this statement then you’ll have to purchase his book, “JavaScript: The Good Parts” or, for a brief overview, watch the Google Tech Talk.

In some ways JavaScript could be considered just as lax as HTML when it comes to what is acceptable and what isn’t. For example, most browsers will let you get away with HTML that looks like this:

<ul
id =list>
    <strong><li>One
    <strong><li>Two
    <strong><li>Three

And, similarly, most, if not all, browsers will let you get away with JavaScript that looks like this:

function muahaha() {
    myarray = new Array()
    myarray['name1'] = "056"
    something = parseInt( myarray['name1'] )
    if(something==56)
        for (i=0;i<myarray.length;i++) if(myarray[i] != null) return true
    return false
};

How many things can you count in the above code that are either bad practice or just incorrect usage of the language? If we go by JSLint then there are a total of 16 problems with it! Plus there are a couple that aren’t noticed by JSLint (using an array as an object & accessing myarray.length on every iteration). That’s 18 altogether! Yet, all browsers will run this code quite happily without throwing a single error.

Technically, it’s all legal JavaScript (minus the extra semi-colon at the end), so I’d expect all browsers to munch it up without complaining.

So, if it works1, then why should you take that extra step to ensure best practices; what’s the point and who will benefit?

For starters, there’s you! When you need to maintain or add to this code you’ll find yourself spending many more minutes doing so than if the original code has been written with best practices in mind. Although, honestly, you are the last person that you should be worrying about. What on earth is another developer going to make of this?

Good practices exist for a reason; not following them generally leads to bad things. Don’t use JSLint because you have to, use it because you want to!

1The function won’t work as expected (parseInt('056') !== 56) but it will “work”; as in, it won’t throw any errors. Actually, just completely ignore the muahaha function; it doesn’t do anything; it’s just an example of awful code.

Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!