Search code examples
javascriptjslint

Jslint variable already defined even in a separate scope?


With the following code JsLint warns that y is already defined in the 2nd block. I do this fairly often and don't think it is a syntax error since the variable is defined in a different block.

Should I really be using different variable names even though it is in a different block? Is the scope defined by the code block of the if statement or only scoped for a function block?

function x() {
  if (condition1) {
    var y = 0;
    // use y
  }
  if (condition2) {
    var y = 20;
    // use y
  }
}

Solution

  • Declare it once

    function x() {
        var y;
        if (condition1) {
            y = 0;
        }
        if (condition2) {
            y = 20;
        }
    }
    

    JS will have block scoping in the future, but it's not widely implemented yet.