Fork me on GitHub

JSLint Error Explanations

JSLint will hurt your feelings. It's time to make them better!

Combine this with the previous 'var' statement

When do I get this error?

JSLint will throw the "Combine this with the previous 'var' statement" error when it encounters multiple variable statements within a function. Here's an example in which we attempt to declare two variables x and y with two separate var statements:

Why do I get this error?

This error is raised to highlight a lack of convention and could also indicate a misunderstanding of how the language works. In many languages, you have the concept of block scope, in which variables can be declared within a block and scoped only to that block. JavaScript does not have block scope. Instead, it has function scope, in which variables can only be scoped to a function. This error is raised to help prevent the misunderstanding of code like this:

In the above example, the variable y is declared regardless of whether the if statement body is entered or not. It is only assigned a value when the if statement body is executed, but it's declared (and will have a value of undefined) no matter what.

To help prevent the misunderstanding that JavaScript exhibits block scope, JSLint will raise this warning to get you to declare all variables at once. You can fix it by moving the declaration of y out of the block and combining it with the declaration of x:

The fact that JSLint does not allow you to simply have multiple variable statements outside of the block is just the coding convention preferred by the author, Douglas Crockford. The use of the comma to group variable declarations into a single statement can make the code easier to follow. The use of the comma character in variable statements is documented as follows (ES5 §12.2):

VariableStatement :
    var VariableDeclarationList ;

VariableDeclarationList :
    VariableDeclarationList , VariableDeclaration

It's worth noting that in this case the comma is not interpreted as a grouping operator, but is rather part of the syntax allowed in a variable statement.

James Allardice

This article was written by James Allardice, an enthusiastic young JavaScript developer at Global Personals (we're looking for developers so please apply). He is passionate about writing clean, maintainable JavaScript and uses JSHint every day to help achieve this.

You can follow him on Twitter, fork him on GitHub and find him on Google+.

Proceeds generated by this site are donated to help advance other open source projects

comments powered by Disqus