Combining 'var' statements

1k views Asked by At

JSLint is throwing problems telling me to Combine this with the previous 'var' statement but I'm not sure how I'd do it correctly with my code:

var len = results.rows.length, i;
//loop around each record in the database
for (i = 0; i < len; i++) {
    var singleRecord = results.rows.item(i);

    //create list
     var individualRecord = '';
     individualRecord = '<li><a href="#info" id="anIndividualRecord" data-key="' + individualRecord.id + '" >';

it's telling me to combine the three var statements in there but if anyone could advise me as to how to do this without creating more problems, that would be much appreciated.

4

There are 4 answers

0
Bart Jedrocha On

Do it all within your top var declaration

var len = results.rows.length, i, inidividualRecord, singleRecord;

for(i=0; i< len; i++) {
  singleRecord = results.rows.item(i);

  individualRecord = '<li><a href="#info" id="anIndividualRecord" data-key="' + singleRecord.id + '" >';
}
0
Paul S. On

Combining multiple vars from the same scope is as simple as removing the var statement from one line and appending the related identifiers to a different var in the same scope.

var len = results.rows.length,
    i,
    individualRecord; // added identifier, only need one var'd copy of each identifier

//loop around each record in the database
for (i = 0; i < len; i++) {
    individualRecord = results.rows.item(i); // removed var

    //create list
     individualRecord = ''; // removed var
     individualRecord = '<li><a href="#info" id="anIndividualRecord" data-key="' + individualRecord.id + '" >';
2
Christoph On

There are basically three things you can do with a variable: Declaration, Initialization and Assignment. The keyword var indicates a variable declaration, whis is only done once for each variable. This often comes together with the Initialization, setting the initial value of the variable. The correct way is:

// add individualRecord here
var len = results.rows.length, i,singleRecord, individualRecord;

//loop around each record in the database
for (i = 0; i < len; i++) {
    // omit the "var" here
    singleRecord = results.rows.item(i);

    // and here as well
     individualRecord = '';

Javascript does some nasty stuff called "hoisting", so it's important to know the subtle differences.

1
ariel_556 On

You cannot re-declare a variable in this case you was doing that: individualRecord.
and jsHint probably is throwing that you need to combine your var declarations due hoisting in JavaScript.

(function () {
  var len = results.rows.length,
    i,
    individualRecord,
    singleRecord;

  for (i = 0; i < len; i++) {
    singleRecord = results.rows.item(i);
    individualRecord = '';
    individualRecord = '<li><a href="#info" id="anIndividualRecord" data-key="' + individualRecord.id + '" >';
  }
}());