Why does JSLint complain about "Unexpected 'else' after 'return'"?

JavascriptJslint

Javascript Problem Overview


JSLint complains that the following (useless example) code is invalid:

(function (x) {
    "use strict";
    if (x === 1) {
        return 1;
    } else if (x === 2) {
        return -1;
    }
    return 0;
}(1));

> Error: > Problem at line 4 character 9: Unexpected 'else' after 'return'. > > return 1;

Is it seriously suggesting that it's bad to use return statements inside an if/else structure?

It thinks this version is fine:

(function (x) {
    "use strict";
    var returnval = 0;
    if (x === 1) {
        returnval = 1;
    } else if (x === 2) {
        returnval = -1;
    }
    return returnval;
}(1));

Javascript Solutions


Solution 1 - Javascript

It's just telling you that else after return is superfluous. The following is fine:

(function (x) {
    "use strict";
    if (x === 1) {
        return 1;
    }  
    if (x === 2) {
        return -1;
    }
    return 0;
}(1));

Solution 2 - Javascript

What I've found w/ jslint is that if you adhere to the rules - 50% are ridiculous yet have no negative impact on your code. The other 50% ( or so ) will give you a good benefit. So do it for the other 50%. This particular example forces you to be explicit about the inverse of a condition or similar...instead of letting it be implicit with an else...same applies to if / else I mean.

Solution 3 - Javascript

Its better to have a function always return something as it adds consistency. JSLint is known to be quite strict and hurting programmers' feelings. Cant help it. Personally I think version 1 is fine

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHalView Question on Stackoverflow
Solution 1 - JavascriptgeorgView Answer on Stackoverflow
Solution 2 - Javascriptmorph_master_flexView Answer on Stackoverflow
Solution 3 - JavascriptJaseemView Answer on Stackoverflow