Search code examples
javascriptsyntaxduplicate-detection

Avoid comma expressions and duplicate declarations


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


Solution

  • 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);
    }