javascript - Jslint variable already defined even in a separate scope? - Stack Overflow

With the following code JsLint warns that y is already defined in the 2nd block. I do this fairly often

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
  }
}

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
  }
}
Share Improve this question asked Oct 16, 2013 at 17:43 BrennanBrennan 11.7k16 gold badges68 silver badges86 bronze badges 1
  • I would not suggest using var at all. This will only expose y to everything else of the if scope that you have defined, which could be harmful given where and what y means to the function/global scope. Use let instead. - stackoverflow./a/11444416/3670089 – Yashash Gaurav Commented May 26, 2020 at 16:19
Add a ment  | 

3 Answers 3

Reset to default 8

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.

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./a/11444416/3670089

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745392828a4625742.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信