I stumbled across this message recently during the course of developing a bespoke jQuery plugin for one of our systems.

The offending code in question was

/*****************************************************************************/
/*Private functions.
/*****************************************************************************/

Given its structure, I found myself blinded to the offending code until I spotted that I had indeed omitted the closing ‘*/’ from the second line.

The message it yielded in full was:

Stopping, unable to continue. (4% scanned).

This message is easy enough to understand, but it’s one of those that causes JSLint to halt in its tracks

The omission of a closing statement to any block of code can result in inadvertently nesting any proceeding code. Block comments are more forgiving of the omission, because the second opening ‘/* will be treated as a comment itself.

However, consider the following:

/*Private functions.    /*Nested Comment*/   */

In the above code, the first close-comment will close everything, and the second will be left dangling. This is even shown up by the syntax-highlighter (if you can see it).

One user did ask this question of Douglas Crockford, who responded

JSLint stops because it sees comments that are nested. That is usually
an indication of a serious coding error. In the face of such errors,
JSLint stops.

So there we have it. Don’t nest your comments.

This article is one of a series on the error and warning messages produced by JSLint.

, ,

When referring to function arguments in JavaScript, we almost always refer to them by the name by which they were passed:

function foo(a) {
    var b = a;   //refer to the function parameter 'a',
    //....
}

However, there is an object representing these arguments to which we can refer. This is the arguments object.

This object provides us with some useful properties, which include .length and .callee. It also allows us to refer to the argument by position like so:

function foo(a) {
    var b = arguments[0];
}

It is this use of the arguments object that JSLint complains about. Variables are given names to identify what they are and what they mean. There are a valuable tool for writing self-documenting code, and referring to them in any other way makes little sense. You’re also relying on the argument being in a particular position. If you ever change the order of the arguments in the function definition, you’ll have to change the index by which you reference each argument.

Moreover, unless your variable name is longer than 12 characters, you will require  more keystrokes to refer to the arguments themselves. In addition to this, opimisers like GZip which can give variables and arguments shorter names for compression and obfuscation purposes are likely to skip over these instances, reducing the compression capability of your code.

Refer to this post on JavaScript arguments at seifi.org for more information on the arguments object.

Special thanks to this article at Programming Goodies for highlighting this as missing from my list of JSLint Errors.

A Guide To JSLint Messages

This article is one of a series on the error and warning messages produced by JSLint.

, , ,

Principles

Most developers are have instilled within themselves certain fundamental core programming practices. Possibly the most famous of these is the DRY (Don’t Repeat Yourself) Principle, which states that duplication can lead to maintenance nightmares, poor factoring, and logical contradictions.

But as with many principles in programming, there are always trade-offs, and times where the rigorous application of a principle can be unhelpful and even counter-productive.

The counterpart to DRY is WET (Write Every Time), and there are scenarios where it makes sense to duplicate code, as described in the articles: Write Every Time Dilutes performance Bottlenecks and Beware The Share.

The JSLint Error

Another principle that is preached almost religiously is the efficient management of resources, and one strategy for doing this is to allocate any resources as late as possible, and  release them as early as possible. The use of block scoping is a particularly common key for achieving this.

This gives rise to code similar to the following:

var a = 1;
if (x === a){
    var b = 2; //'try' giving variable 'b' block scope
    //do other stuff
}

In languages such as C++, C# and Java the above convention would limit the scope and lifetime of the variable ‘b’ to the ‘if’ block.

JavaScript, however, has no block scoping, and any variables declared within a block will be ‘hoisted’ to the top of the nearest scope when the code is picked up by the compiler. This is either the nearest containing function, or global scope. In short, this will make them visible outside the originally intended scope.

JSLint is all about reducing bugs, and had the author of this StackOverflow question run their code through JSLint, then they may never have had to ask a question at all.

Adding (Pseudo) Block Scoping

If you really wanted to enforce scoping down at this level then the following convention might help:

var a = 1;
if (x === a){
    (function(){
        var b = 2; //give variable 'b' (pseudo) block scope
        //do other stuff
    }());
}

Here we’ve wrapped the code in an anonymous function, and invoked it immediately (thanks to the set of parens at the end).

But JSLint Stops Scanning

Yeah, sometimes it does.

I have tried to remain neutral in all my posts on JSLint messages to date. Here, however I am going to jump off the fence and offer a sentiment of bafflement.

JSLint deems some errors so serious that it immediately ceases scanning. For me this is understandable in the event that it encounters utterly unparsable code and literally cannot continue, however, I just don’t understand why it must stop dead with the following:

for (var x=0; x<10 x++){
    //do something
}

And it appears I am not alone. A very similar query posted on the JSLint GitHub repository failed to yield any explanation before the thread was closed.

Any ideas anyone?

A Guide To JSLint Messages

This article is one of a series on the error and warning messages produced by JSLint.

, ,

Periodically, I check the JSLint update history on GitHub to see what’s going on, and what significant updates have been included.

So, imagine my surprise when I saw a simple one-line comment on a June 12, 2011 edit:

eqeq

I did a quick diff on the source code to see this following line added:

 //     eqeq       true, if == should be allowed

This means that you can now configure JSLint to ignore uses of ‘==’, where previously it would have insisted you should use ‘===’

At the time of writing it hadn’t been updated on the JSLint front page, however testing locally with the following yielded no ‘==’ related warnings:

    /*jslint eqeq: true*/
    var x = 0;
    if (x == 1) {
        alert("test");
    }

I always recommend that use the ‘===’ in this instance anyway, but I am aware of the differing opinions surrounding it. Ultimately, you can make your own decision (and it is ‘on’ by default so you have to opt-out).

, ,

An incorrect placement of the ‘break’ statement within a loop will yield this error message. As shown in the following example:

function MyFunc(){
    var x = 0;
    for (x=0; x<10; x++){
        //do something
        break;
    }
}

Here, we will never reach the second iteration of the loop.The ‘break’ statement will kick us out at the end of the first time around. Break statements used in this way should always be wrapped in a conditional statement.

At best this is redundant code that was never cleared up properly, and, at worst, this is some sort of bug that is yet to be identified.

A Guide To JSLint Messages

This article is one of a series on the error and warning messages produced by JSLint.

, , ,

In languages where compilation of code is required up-front before it can be executed, the developer often has the luxury of being warned about unused or unreachable code by the compiler.

For JavaScript, we have no such luxury, however, JSLint is there to emulate some of the features that a compiler would provide.

So, when we write code that contains unused variables, JSLint will helpfully warn about us about it. The following code sample will yeild this error:

function MyFunc(){
    var x = 0;
    for (x=0; x<0; x++){
        //do something
        var y = 0;
    }
}

At best this is redundant code that was never cleared up and, at worst, this is some sort of bug that is yet to be identified.

A Guide To JSLint Messages

This article is one of a series on the error and warning messages produced by JSLint.

, , ,

This message is documented quite concisely on the JSLint instructions page:

JSLintexpects that a returnbreakcontinue, or throw statement will be followed by a } or case or default

At best, the presence unreachable code is indicative of general laziness on behalf of the developer, and, at worst, it may highlight a potential bug. Either way, JSLint is fully justified in raising the error.

The following code shows a scenario where this might arise:

function MyFunc(){
   var x = 0;
   return x;
   x++;
}

JSLint is also savvy enough to look within conditional statements…

function MyFunc(){
    var b = false;
    if (b){
        return 1;
    }
    else{
        return 2;
    }
    return 3;
}

…loops…

function MyFunc(){
    var x = 0;
    var y = 0;
    for (x=0; x<10; x++){
        if (x<5){
            break;
            y++;
        }
    }
}

…and the not often seen “throw” statement.

function MyFunc(){
    var x = 0;
    throw "MyError";
    x++;
}

This is just another way that JSLint can help you identify potential issues earlier in the development process.

A Guide To JSLint Messages

This article is one of a series on the error and warning messages produced by JSLint.

, ,

Overview

This is one of the longer messages that JSLint reports. Here it is in full:

The body of a for in should be wrapped in an if statement to filter unwanted properties from the prototype.

Here, JSLint is counselling you against making the assumption that the only object members ever found will be those that have been explicitly added to it (and not, say, to a base object).

For ‘Member’ In ‘Object’

Firstly, let’s recreate it:

var a = {b:1, c:2};
var x = 0;
for (x in a){
    alert(a[x]);
}

In the above code, we are creating a simple object using the object literal notation, and then iterating over its member. All seems well when we run it, as can be seen as this JSFiddle. So, what is the reason for JSLint’s complaint?

Here we are relying on the fact that elsewhere in our code base no-one will ever tinker with the underlying object, and add some unexpected properties or methods. Consider the following line of code:

Object.prototype.somefn = function(){};

Here, the prototype keyword allows us to extend the underlying object, effectively adding a new method somefn to every object in our system. Its effect can be seen in this JSFiddle – as well as the “1″ and “2″ alerts we also get the function definition alerted.

Clearly we want to filter out properties or methods that are not part of the immediate collection. But How?

We could extend out function to check for properties explicitly, like so:

function AlertAll(o){
    var x = 0;
    for (x in o){
        if (x === 'b' || x === 'c'){
            alert(o[x]);
        }
    }
}

(Also in this updated fiddle)

But this isn’t very scalable, of, for that matter, very  good! It introduces all sort of dependencies, coupling, technical debt, and other general bad words when it comes to programming. So how do we search for an objects own properties?

Easy! We check the hasOwnProperty property of the object, like so:

function AlertAll(o){
    var x = 0;
    for (x in o){
        if (o.hasOwnProperty(x)){
            alert(o[x]);
        }
    }
}

(Also in this further updated fiddle)

For ‘Element’ in ‘Array’

Done correctly, the for…in construct can be quite useful for iterating over object members (as shown in the above example). In JavaScript, every object has an equivalent array representation, so we can access the members using the array literal notation []. So, by logical extension, we can also use the for..in construct to iterate over a pure array.

This is madness inviting atrophy, as shown in the following code:

function AlertAll(arr){
    var x = 0;
    for (x in arr){
        alert(arr[x]);
    }
}
//We don't actually need to extend Array to show the ensuing atrophy
//Array.prototype.somefn = function(){};
var a = [0,1];
AlertAll(a);

If you don’t mind having to dismiss about 30 dialog boxes then feel free to see the problems at this JSFiddle. By examining the hasOwnProperty property as before we can, of course, solve this, but this is missing the point somewhat, which is “What is the point?”

We all (should?) know how to iterate over an array in JavaScript. We do it with a standard for loop like so:

function AlertAll(arr){
    var x = 0;
    for (x=0; x < arr.length; x++){
        alert(arr[x]);
    }
}

var a = [0,1];
AlertAll(a);

Provided for all its pointlessness at this updated JSFiddle.

Resouces

As always, a couple of resources from Stack Overflow:

Stack Overflow: What does the JSLint error ‘body of a for in should be wrapped in an if statement’ mean?

Stack Overflow: JavaScript: JSLint error “The body of a for in should be wrapped in an if statement to filter unwanted properties from the prototype”

A Guide To JSLint Messages

This article is one of a series on the error and warning messages produced by JSLint.

, , ,