59

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));
Hal
  • 884
  • 1
  • 7
  • 12

3 Answers3

99

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));
georg
  • 211,518
  • 52
  • 313
  • 390
  • 56
    You're right. I personally prefer an if-else chain though, it feels like it gets across the intent of the code more clearly. – Hal Feb 28 '12 at 11:21
  • 3
    @Hal And especially useful when refactoring, when you actually decide to use a single `return`. An omitted `else` will be an error then. – Sulthan Aug 09 '14 at 08:06
4

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.

  • 1
    Disagree. Yes, 50% will not provide a "no negative impact". But it's only concerning the code itself. Think about the future maintenance, the near debug time and other developers who don't code like you or who are not ninjas. JSLint in its strict mode offers you to code by a standard/normalized way which allow anyone to read/understand/code with everybody, don't regarding to experience/skills or time. Yes it's strict, it's hard to respect but when your code is compliant, it's a "cross-human code". – MathKimRobin Dec 08 '14 at 16:52
1

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

Jaseem
  • 2,236
  • 6
  • 28
  • 35