1

What's the meaning of this "Function definitions may not appear within if statements, while loops, or any other statements." I'm quite confuse with this statement.

  • 2
    http://stackoverflow.com/questions/3037598/how-to-get-around-the-jslint-error-dont-make-functions-within-a-loop – elclanrs Dec 17 '12 at 06:47
  • 2
    Show us the offending code and tell us what is generating that message. – jfriend00 Dec 17 '12 at 06:50
  • Where exactly does this message come from? – Felix Kling Dec 17 '12 at 06:50
  • @FelixKling it's from the book _JavaScript: The Definitive Guide_ – thebeatles1991 Dec 17 '12 at 06:56
  • 1
    A search for this phrase brings up Flanagan's book, page 91. However, I just tried it out in nodejs *and* firefox, and I have no problem putting a function in an 'if' statement, even **within the condition**. It seems like something you might want to avoid, but obviously they may appear, at least in some javascript engines. – user4815162342 Dec 17 '12 at 06:56
  • 1
    In ES5, function declarations are not allowed inside code blocks. However, modern browsers do allow it. Unfortunately, modern browsers are not consistent in how they handle the situation. ES6 is going to permit function declarations inside code blocks in order to specify a standardized behavior that all browsers must follow. So in summary, that statement will be out of date in a year or two, but it'll still be considered bad practice to put a function declaration in a code block. – Nathan Wall Dec 17 '12 at 07:20

1 Answers1

0

One issue with what you're reading in the book is that a function definition (which is different than a function assignment) is essentially hoisted to the top of the host function in some browsers so putting it inside a statement (like inside an if statement) is downright misleading. The code will make it look like the function will only be defined if that branch of the if statement executes, but that will not necessarily be the case. So, it's a bad practice. It probably works in many cases, but is a bad practice.

So, rather than this:

function main(foo) {
    if (foo) {
        function internal() {
            // code here
        }
        // code here
    }
}

Put the internal function up at the top;

function main(foo) {
    function internal() {
        // code here
    }
    if (foo) {
        // code here
    }
}

FYI, in strict mode internal function definitions are only allowed at the top. Condition function assignments can always be done with this syntax:

var internal;
if (foo) {
    internal = function() {}
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979