Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 876
Justin Beaudry Avatar asked Apr 20 '26 11:04

Justin Beaudry


1 Answers

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.

like image 86
Denys Séguret Avatar answered Apr 22 '26 23:04

Denys Séguret