Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through FileList declaration

I am trying to wrap my mind around a particular for loop declaration, but I had no success so far. The code snippet allows you to read a file input and loop through all the objects thanks to a for loop:

<script>
  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // files is a FileList of File objects. List some properties.
    var output = [];
    for (var i = 0, f; f = files[i]; i++) {
      output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
                  f.size, ' bytes, last modified: ',
                  f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
                  '</li>');
    }
    document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
  }

  document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script> 

Now, I wonder when does this for loop

for (var i = 0, f; f = files[i]; i++)

stops. Shouldn't the second parameter be a comparison parameter like " === , < , > " and so on ?

I can see that on each loop it is assigning to the variable 'f' the value of every object input in files[i], but I don't get why it is declared like that and how does it works. What is the difference between the aforementioned and this?

var f;
for (var i = 0;i<files.length; i++) {
      f = files[i];
}
like image 216
iomv Avatar asked Apr 03 '26 03:04

iomv


1 Answers

Assigment always returns the assigned value, so the statement f = files[i] returns the file, which is a truthy value, until there are no more files in the fileList, then it returns undefined, which is falsy, and the loop stops.

The reason it stops is because a for loop consists of three expressions

for ([initialization]; [condition]; [final-expression]) { statement

The "condition" is an expression to be evaluated before each loop iteration.
If this expression evaluates to true, the statement is executed, if it evaluates to false, like undefined would, the statement is not executed.

like image 164
adeneo Avatar answered Apr 08 '26 04:04

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!