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';
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With