Search code examples
javascriptlexical-scope

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?


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.