Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function was used before it was defined - JSLint

JSLint does not like this code saying "'b' was used before it was defined"

var a = function () {
        b();
    },

    b = function () {
        alert("Hello, world!");
    };

a();   

but perfectly happy with this

var a, b;

a = function () {
    b();
};

b = function () {
    alert("Hello, world!");
};

a();   

But I am not defining anything in my second code snippet. I am merely declaring variable b.

So why is JSLint doing this? Is there a reason I should be declaring all my functions first?

PS I understand I could have just changed order of a and b, but in real project my functions are event handlers and sometimes they call each other, so it is probably not possible.

like image 461
Evgeny Avatar asked Oct 18 '12 20:10

Evgeny


2 Answers

If your code is well-written and object-oriented, it is possible to declare your functions before they are used. But JSLint sets a lot of standards that really have little relevance to the functionality of your application, and I really doubt there are any performance implications declaring functions one way or the other.

like image 88
Micah Henning Avatar answered Oct 07 '22 18:10

Micah Henning


So why is JSLint doing this? Is there a reason I should be declaring all my functions first?

Yes, otherwise there might be some unexpected errors. Your code works because of JavaScript's "Hoisting". This mechanism pulls up all declarations, implicit or explicit and can cause some unexpected results.

Consider this code:

var s = "hello";    // global variable
function foo() {
    document.write(s);   // writes "undefined" - not "hello"
    var s = "test";      // initialize 's'
    document.write(s);   // writes "test"
};
foo();

It's being interpreted as follows:

var s = "hello";    // global variable
function foo() {
    var s;               // Hoisting of s, the globally defined s gets hidden
    document.write(s);   // writes "undefined" - now you see why
    s = "test";          // assignment
    document.write(s);   // writes "test"
}
foo();

(example taken from the german Wikipedia page: http://de.wikipedia.org/wiki/Hoisting)

like image 11
user654123 Avatar answered Oct 07 '22 16:10

user654123