Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSLint - problems declaring variables

The following code passes JSLint:

var sGreeting = 'hello world';

switch (sGreeting)
{
case 'Hello world!':
    var a = 'some a value';
    break;
case 'Kamusta mundo!':
    var b = 'some b value';
    break;
case 'Salut le Monde!':
    var c = 'some c value';
    break;
default:
    break;
}

However, once I put that code in a function, JSLint complains that I should Combine ... with the previous 'var' statement. If I follow JSLint, I would be defining variables that may never need to be used. How should I deal with this problem? Here's the code followed by JSLint's errors:

function foo()
{
    'use strict';
    var sGreeting = 'hello world';

    switch (sGreeting)
    {
    case 'Hello world!':
        var a = 'some a value';
        break;
    case 'Kamusta mundo!':
        var b = 'some b value';
        break;
    case 'Salut le Monde!':
        var c = 'some c value';
        break;
    default:
        break;
    }
}


Error:
Problem at line 9 character 7: Combine this with the previous 'var' statement.
var a = 'some a value';

Problem at line 12 character 7: Combine this with the previous 'var' statement.
var b = 'some b value';

Problem at line 15 character 7: Combine this with the previous 'var' statement.
var c = 'some c value';
like image 671
StackOverflowNewbie Avatar asked Sep 09 '11 06:09

StackOverflowNewbie


1 Answers

The only scope in javascript is functional scope (braces do not provide scope), so those vars in the switch statement are being hoisted to the top of the function.

What jslint is suggesting is this:

function foo() {
    'use strict';
    var a, b, c, sGreeting;

    sGreeting = 'hello world';

    switch (sGreeting) {
    case 'Hello world!':
        a = 'some a value';
        break;
    case 'Kamusta mundo!':
        b = 'some b value';
        break;
    case 'Salut le Monde!':
        c = 'some c value';
        break;
    default:
        break;
    }
}
like image 123
steveax Avatar answered Sep 29 '22 18:09

steveax