1

In order to clear up my code I have been paying attention to all of the hints in Web Storm. The following duplicate declaration errors have confused me.

In the following code, is the double use of var necessary (or advised) to prevent a global variable? (or could I remove the second var in from of s:

function run(x) {
    if(x == 5) {
        var s = 'Yes',
            bar = 1,
            baz = 2
    } else {
        var s = 'No',
            bar = 1,
            baz = 2
    }
    console.log(s);
}

Also, if I do remove var in the else condition, I get a comma expression error, indicating that my code may be "overly clever".

Writing

else {
    bar = 1,
    baz = 2
 }

Seems to me to be bad syntax

Startec
  • 12,496
  • 23
  • 93
  • 160

2 Answers2

3

For this I would use:

function run(x) {
  var s = (x === 5) ? 'Yes' : 'No';
  var bar = 1;
  var baz = 2;

  console.log(s);
}

You're getting a duplicate declaration error at present because the variables are in the same scope.

jabclab
  • 14,786
  • 5
  • 54
  • 51
  • And also, the error in else is because the first var declaration ends with semi-colon. Subsequent comma on bar will produce an error. – Abhitalks Jun 19 '14 at 11:02
1

If sticking to the original code, then cleanest solution would be:

function run(x) {
    var s, bar, baz;

    if(x == 5) {
        s = 'Yes';
        bar = 1;
        baz = 2;
    } else {
        s = 'No';
        bar = 1;
        baz = 2;
    }
    console.log(s);
}
Ingmars
  • 998
  • 5
  • 10