Search code examples
jqueryanonymous-functionjslinteventhandler

Why does JSLint say "anonymous function does not always return a value" for an event handler?


When I JSLint this code:

$(document).keydown(function(e){ 
    if ($("#chaptersFunctionality").length !== 0) {
        if (e.keyCode == '13')
            return false;
        if ($("#kelvin").val() === "" && $("#caleb").attr("title") === "Show all steps") {
            switch(e.which){
            case 39:    if ((parseInt(currentAnchor)+1) < parseInt(maxi))
                expandMe(++currentAnchor);
                break;
            case 37:    if (currentAnchor > 0)
                expandMe(currentAnchor-1);
                break;
            }
        }
    }
});

...I get plenty of warnings, most of which I grok, but this one has me stumped: "anonymous function does not always return a value"

Why does it say this? An event handler is not an anonymous function, is it? And it's not returning any value anyway, is it? So what does this mean, and what would [moll,pac]ify the linter?


Solution

  • JSLint warns you any time a function has some branches that encounter a return and other branches that terminate without encountering a return. JSLint thinks that a function should either always explicitly return a value or never explicitly return a value. A function that sometimes explicitly returns a value earns itself a warning. Your code does return false in one case and otherwise never uses return.

    If you want to pacify JSLint, you may place a return undefined; at the bottom of your function so that it always explicitly returns something.

    Now, for my opinion:

    When it comes to event listeners, it is 100% acceptable to return value only sometimes. The browser's internal engine that uses your event listener return value is already programmed to accept a return value or the lack of a return value.

    Because the practice of not returning a value in an event listener is perfectly normal, this does not harm the readability of your code. I think you can safely ignore JSLint in this case.