helpermethod
helpermethod

Reputation: 62185

JS Scoping issue

Consider the following piece of code:

function processParagraph(paragraph) {
    if (paragraph.charAt(0) === '%') {
        for (var level = 0; paragraph.charAt(level) === '%'; level++) {}

        return {
            type: 'h' + level,
            content: paragraph.slice(level + 1)
        };
    }

    return {
        type: 'p' + level,
        content: paragraph
    };
}

When I check this with JSLint, it complains that level in the second return statement is used out of scope..

But why? AFAIK, JavaScript has Lexical Scoping/Function Scope. As there are no nested functions, the code should be perfectly valid. Or am I missing something?

Upvotes: 2

Views: 127

Answers (3)

Quentin
Quentin

Reputation: 943586

JSLint is a Lint, not a plain syntax checker.

Function level scoping is something that many developers are not used to and don't expect. JSLint's author considers it good style to declare variables in such a way that they would still be compatible if block scoping were used.

Upvotes: 2

sje397
sje397

Reputation: 41822

One a variable is defined using var it is visible to the whole function.

What you have there will use level in the final return even though it has never been defined.

I would put

var level = 0;

...at the top of the function, and not declare it in the for loop.

Upvotes: 2

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143099

What it probably means is that level is not set, but used for the other execution path.

Upvotes: 1

Related Questions