Justin Beaudry
Justin Beaudry

Reputation: 864

Comma after variable assignment in Javascript

function ReplaceContentInContainer(matchClass,content)
    {
    var elems = document.getElementsByTagName('*'), i;
    for (i in elems)
        {
        if((" "+elems[i].className+" ").indexOf(" "+matchClass+" ") > -1)
            {
            elems[i].innerHTML = content;
            }
        }
    }

I'm trying to figure out what the comma does in the variable assignment ('*'), i; and what that means in the for (i in e) loop.

My best guess is that e is assigned to both all the elements in the document node as well as i. So does that mean that i is a count or reference of the number of elements in the array e (is it an array?)?

edit: Okay. It's just instantiating the variable (i) and then i, in the for loop, counts all the elements in the object elem.

Upvotes: 3

Views: 1452

Answers (3)

Minko Gechev
Minko Gechev

Reputation: 25682

That comma is because you define the variable i in the local scope, it's simply part of the var statement. If there wasn't a comma i would be a global.

Your statement is the same as:

var elems = document.getElementsByTagName('*');
var i;

If you use tool for static analysis of the quality of your code, like JSLint for example, it'll force you to write:

var elems = document.getElementsByTagName('*'),
    i;

In few reasons:

  1. You define both variables (so you don't have globals)
  2. You don't have extra var (you write less... :-))
  3. Your code is more readable than the one line version
  4. You define all your variables at the same place which is easier for reading than:

    for (var i in elems) { //do something }

There's similar concept in perl, for example:

my ($var1, $var2);

In JavaScript it's the same but you don't need to put the variables inside a list.

Upvotes: 2

bipen
bipen

Reputation: 36541

i is the part of the var statement.. so it is just creating a new variable... you code is same as

var elements=document.getElementsByTagName('*');
var i;

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382304

That simply separate the declarations.

var elems = document.getElementsByTagName('*'), i;

is the same as

var elems = document.getElementsByTagName('*');
var i;

One is more concise, the other one might be seen as more readable.

In your precise case, you could have used

var elems = document.getElementsByTagName('*');
for (var i in elems)

which would be, in my opinion, the best as the purpose of i would have been obvious.

As the scope of a variable is the function (or global) and not the block, it would have been exactly identical.

Upvotes: 6

Related Questions