JSLint error: Move all ‘var’ declarations to the top of the function

Update June, 2017: Subject to support (e.g. if you’re not running JavaScript in Internet Explorer 10 or below), you should look into using let instead of var.

For example: for(let i=0; ...; i++)


There’s no way I’m going to put var i; from a for(var i=0; ...; i++) at the top of my functions. Especially when The JavaScript Specification has it as an acceptable syntax in the for section (12.6). Also, it’s the syntax Brendan Eich uses in his examples.

The idea of moving the declaration to the top is that it is supposed to more accurately reflect what happens under the hood, however, doing so will only reflect, not affect.

For me, this is a ridiculous expectation for for iterations. More so because JSLint stops processing when it detects it.

Whether having variables declared at the top of a function is more readable is debatable. I personally prefer iterator variables to be declared when they are used. I don’t care if the variable is already created internally, I’m initialising it here so I am safe.

I would argue that declaring an iterator variable where they are used ensures they are not accidentally made global (if you move the loop out into another function, the iterator variable moves with it). This is much more maintainable than having to maintain variable declarations at the top of functions.

For now, I’m using http://www.javascriptlint.com/online_lint.php because it seems to focus on the important stuff.

Leave a Comment