0

I have some code to make a Drag&Drop with Vanilla JS, and i have these functions:

function HandleDrop(e) {
    var dt = e.dataTransfer;
    var files = dt.files;

    HandleFiles(files);
}

function HandleFiles(files) {
    ([...files]).forEach(UploadFile); // "UploadFile" is a function to make an Ajax call, is not important
}

"HandleDrop" is added to the "drop" event of a div and i don't understand what's the meaning of "([...files])". I tried to find in Google but the parentheses and square brackets aren't used for the search (google skip it).

  • 1
    it creates a `shallow copy` of files array. you can read about the `spread operator` – AZ_ Jan 31 '20 at 09:20
  • 2
    Yeah, it's *really* annoying to search for some of the symbols used in programming. If it's function name you can at least count on finding it, if it's just random symbols - tough luck. At least on SO there is the [What does this symbol mean in JavaScript?](https://stackoverflow.com/questions/9549780/what-does-this-symbol-mean-in-javascript) Q&A which allows you to Ctrl + F and should find most things. Or you can look through each. Not *all* symbols are there but most should be. – VLAZ Jan 31 '20 at 09:25
  • It's worth noting that this specific use of spread relies on features that aren't specified. The [`FileList`](https://w3c.github.io/FileAPI/#filelist-section) interface is not marked as being iterable, so you can't rely on spread working with it. The correct code here would be `Array.from(files).forEach(UploadFile);` (or a boring old `for` loop). Although some implementations may choose to make `FileList` iterable, others may not. Also, *if* `FileList` is iterable in the DOM sense on some impls, it'll have its own `forEach` anyway; [details](https://heycam.github.io/webidl/#idl-iterable). – T.J. Crowder Jan 31 '20 at 09:26
  • (The `()` are also unnecessary.) – T.J. Crowder Jan 31 '20 at 09:35
  • ***Ugh***, Chrome (thus Chromium, Brave, ChromiumEdge), Firefox, pre-Chromium Edge, and iOS Safari make it iterable only in the JavaScript sense. `files[Symbol.iterator]` is a function, but `files.forEach` isn't. Blech. Blech. Blech. I mean, I guess...they're consistent. But blech. And still unspecified. – T.J. Crowder Jan 31 '20 at 09:45

0 Answers0