# How to iterate over FileList in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Jun 5, 2021, updated Oct 8, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-iterate-filelist

> A quick guide to learn how to iterate over a FileList object in JavaScript.

A `FileList` is an array-like object that represents a collection of `File` objects returned by the `files` property of the HTML `<input>` element. You can use this to access the list of files selected with the `<input type="file">` element.

Just like a JavaScript [array](https://attacomsian.com/blog/javascript-arrays), `FileList` has the `length` property that returns the number of files in the list. However, it is not an actual array. So you can not use common array's methods like `slice()`, `map()`, `filter()`, or `forEach()` on a `FileList` object.

Let us say you have got the following HTML element:

```html
<input type="file" id="avatars" multiple>
```

To loop through all the selected files with the above input element (a `FileList` object), you can use the classic [for loop](https://attacomsian.com/blog/javascript-loops#for-loop) as shown below:

```javascript
const input = document.querySelector('#avatars')

// Retrieve FileList boject
const files = input.files

// Loop through files
for (let i = 0; i < files.length; i++) {
  let file = files.item(i)
  console.log(file.name)
}
```

The `item()` method returns a `File` object representing the file at the specified index in the file list. You can also directly access the file using the index notation (`files[i]`). 

## Convert `FileList` to an array

When you convert a `FileList` object into an array, you can use all array methods like [forEach()](https://attacomsian.com/blog/javascript-foreach), `map()`, and `filter()`.

There are multiple ways to convert a `FileList` to an array. I've already explained these methods in the [NodeList to array conversion](https://attacomsian.com/blog/javascript-convert-nodelist-to-array) article.

The [`Array.from()`](https://attacomsian.com/blog/javascript-array-from) is one such method that takes in an array-like object as input and returns an array:

```javascript
const input = document.querySelector('#avatars')

// Retrieve FileList boject
const files = input.files

// Convert FileList to array
const arr = Array.from(files)

// Loop through an array
arr.forEach(file => console.log(file.name))
```

Alternatively, you could also spread operator syntax to convert a `FileList` to an array:

```javascript
const arr = [...files]
```
