Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top