Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
145
rated 0 times [  150] [ 5]  / answers: 1 / hits: 15184  / 15 Years ago, fri, may 1, 2009, 12:00:00

JSLint (with the onevar flag turned on) is flagging some javascript code that I have with the following:



Problem at line 5 character 15: Too many var statements.


I am happy to fix these errors, but I'd like to know, am I doing it for performance or because it is just a bad practice and has a greater potential to introduce bugs in my javascript code. What is the reason behind the onevar flag?



I did look at the JSLint docs for the var keyword but it doesn't specifically talk about why multiple var statements in the same function are bad.



Here is an attempt at an example. Explain how the code will benefit from only having 1 var statement:



function Test(arg) {
var x = arg + 1,
y = cache.GetItem('xyz');
if (y !== null) {
// This is what would cause the warning in JSLint
var request = ajaxPost(/* Parameters here */);

}
}

More From » refactoring

 Answers
43

Javascript does not have block scope. In other languages with it (like c), if you declare a variable in the if statement, you can not access it outside of it, but in javascript you can. The author of JSLint believes it is a bad practice, since you (or other readers) might get confused and think that you can no longer access the variable, but you actually can. Therefore, you should declare all your variables at the top of the function.


[#99618] Saturday, April 25, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kiyam

Total Points: 448
Total Questions: 96
Total Answers: 92

Location: Philippines
Member since Sat, Jul 11, 2020
4 Years ago
;