JsLint Unexpected Continue Error Explained

If you’ve ever had the “pleasure” of running your JavaScript code through JSLint, you’ve probably encounter the following message.

Unexpected continue

Recently, I encountered this message when checking some code I’d written. In an attempt to gain some clarity on what the problem was, I checked out the JS Lint Documentation which tells me to

[a]void use of the continue statement. It tends to obscure the control flow of the function.

While this highlights how continue (and continue) can reduce code clarity, I still don’t feel that’s a very good explanation. If you check out JavaScript: The Good Parts Douglas Crockford doesn’t provide much help either:

The continue statement jumps to the top of the loop. I have never seen a piece of code that was not improved by refactoring it to remove the continue statement.

Crockford, Douglas (2008-12-17). JavaScript: The Good Parts: The Good Parts (Kindle Locations 2861-2864). OReilly Media – A. Kindle Edition.

Not exactly helpful (and a little arrogant, if you ask me). After doing some more research, I’ve discovered that what JsLint (and Crockford, by extension) wants you to do is invert your logic so that the continue> statement is no longer needed.

For example this code:

var i = 0,
    names = ['james', 'sally', 'ray',  'charles', 'kevin', 'dan'],
    numNames = names.length;


for(i = 0; i < numNames; i++) {
    if(names === 'sally') {
        continue;
    }
    // process data
}

Can be refactored to not use the continue statement by inverting the conditional:

var i = 0,
    names = ['james', 'sally', 'ray',  'charles', 'kevin', 'dan'],
    numNames = names.length;


for(i = 0; i < numNames; i++) {
    if(names != 'sally') {
        // process data
    }
}

Hopefully, I’ve provided some clarity regarding JsLint’s rather cryptic error messages. Is there another message you can’t seem to wrap your head around or just plain don’t agree with? Leave a comment below.