Search code examples
javascriptscopejslint

jslint: function out of scope


I've been messing around with JS and various other web-related things lately and kind of learned the whole thing while applying it.

Out of interest I've put my code into a JS validator (jslint.com) and the result is staggering. I do understand most of the warnings, but there is one in particular that I can't get my head around. It reads 'doSomething' is out of scope. Basically, this is the relevant portion, I believe. My entire script is structured like that: ready-function to kick things off and then it goes into the specific functions.

$('document').ready(function () {
    $('#btn').click(function () {doSomething();});
});

function doSomething() {
    console.log('did something');
}

I figured, a variable for instance is "out of scope" if it is declared in an if-expression and used outside of it. Like so:

function whatnot() {
    if (true) {
        var x = 10;
    }
    return x;
}

But how does that translate to my issue? Can you help me understand the problem and maybe give examples for a better code structure (or point me towards some articles that might help?)

Thanks in advance :)


Solution

  • jslint is mistaken. That code will work without any scoping problems.

    However, as a matter of style, you might want to define doSomething() above where it is used. Although $('document').ready doesn't get called until the entire DOM is rendered, and that shouldn't happen until after the script tag is fully parsed. As a matter of style, I prefer to define methods before I call them, and jslink would probably be satisfied if you moved your function definition inside of the ready block.