Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First Expression in a Javascript For Loop - what's with the comma?

I'm working through an HTML5 drag and drop example http://www.sitepoint.com/html5-file-drag-and-drop/, but can't figure out exactly what is happening in the loop at the end of this function-

function FileSelectHandler(e) {

    // cancel event and hover styling
    FileDragHover(e);

    // fetch FileList object
    var files = e.target.files || e.dataTransfer.files;

    // process all File objects
    for (var i = 0, f; f = files[i]; i++) {
        ParseFile(f);
    }

}

As far as I know, the first expression should just be i=0. What is happening with the , f? As long as the files array contains key i, i gets incremented, f is parsed and it then looks for files[i] again, right?

like image 698
Mark Avatar asked May 24 '26 09:05

Mark


1 Answers

In a for loop, you can have multiple initializers separated by commas. That's what you have there, combined with a lazy (and misleading) var. In this particular case, it's equivalent to:

function FileSelectHandler(e) {
    var i, f, files;

    // cancel event and hover styling
    FileDragHover(e);

    // fetch FileList object
    files = e.target.files || e.dataTransfer.files;

    // process all File objects
    for (i = 0; f = files[i]; i++) {
        ParseFile(f);
    }
}

...because var is badly misunderstood in JavaScript. But probably a better example of using multiple initializers would be:

var a = [1, 2, 3], index, len;

for (index = 0, len = a.length; index < len; ++index) {
    // Do something with a[index]
}

There, with the misleading var removed, we can see that there are two distinct initializers at the beginning of the for statement.

like image 54
T.J. Crowder Avatar answered May 25 '26 23:05

T.J. Crowder