Domanda

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
  }
}
È stato utile?

Soluzione

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.

Altri suggerimenti

There is no different scope inside if, for and while statements, but there is in functions.

I know there is accepted answer to this already, but I think what you are looking for is a let statement.

Please refer to this answer to understand variable scoping (let vs var): https://stackoverflow.com/a/11444416/3670089

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top