4

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
  }
}
Brennan
  • 11,546
  • 16
  • 64
  • 86
  • 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. - https://stackoverflow.com/a/11444416/3670089 – Yashash Gaurav May 26 '20 at 16:19

3 Answers3

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.

  • What I am often doing in this project is declaring items which go into an array and I use var to declare the values that I put into the array. I do that because I want to ensure the value going into the array is unique and not reassigned. But maybe that is not necessary. It just seems awkward to declare the var outside the loop when it is a different var each time. – Brennan Oct 16 '13 at 17:50
  • var array = []; var number; for (var i=0;i<10;i++) { number = i; array.push(number); } console.log(array); I just wrote this bit of code and it seems work as I want. I just do not like declaring the var before the loop. – Brennan Oct 16 '13 at 18:12
  • You don't have to I guess, unless jslint matters to you. I'm a little OCD, so it's the way I do it. FWIW –  Oct 16 '13 at 18:14
0

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

Guilherme Sehn
  • 6,727
  • 18
  • 35
  • Thanks, that is what I thought as well though it looks like scoping is supposed to change with more current specs for JS. – Brennan Oct 16 '13 at 18:12
  • 1
    @Brennan - The scope of variables declared with `var` is not going to change. In ES6 you have `let` declarations which are block scoped, but `var` declarations will behave as they do now. – James Allardice Oct 17 '13 at 06:29
0

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

Yashash Gaurav
  • 581
  • 5
  • 9