Reputation: 6916
Can someone explain me what is the meaning of []
in a function parameter, I don't get what the purpose of the []
on [fileEntry]
.
const onDrop = ([fileEntry]: any[]) => {
fileEntry && fileEntry.file(file => processFile(file))
}
Does it convert the fileEntry
to an array? I f yes why that won't work?
const onDrop = (fileEntry) => {
fileEntry = [fileEntry]
fileEntry && fileEntry.file(file => processFile(file))
}
Upvotes: 2
Views: 824
Reputation: 113974
It is array destructuring. It means you pass it an array and it assigns a member of that array to a variable. Basically it is doing this:
const onDrop = (x) => {
let fileEntry = x[0];
fileEntry && fileEntry.file(file => processFile(file))
}
If there are two variables in the square brackets like:
const onDrop = ([fileEntry, options]) => {
fileEntry && fileEntry.file(file => processFile(file))
}
It would do this:
const onDrop = (x) => {
let fileEntry = x[0];
let options = x[1];
fileEntry && fileEntry.file(file => processFile(file))
}
Upvotes: -1
Reputation: 31825
This is called Destructuring assignment: it declares a variable named fileEntry
in the scope of the function, which is assigned to the first item of the function's parameter (which is supposedly an Array
).
Note that the function's parameter may not be an Array
. The only real requirement is the iterator
in order to make destructuring assignment work:
const func = ([first, second, third]) => first + second + third;
const obj = { [Symbol.iterator]: () => [1, 2, 3].values() };
console.log(func(obj));
Upvotes: 2
Reputation: 101728
It's destructuring - the function takes an array as its argument and fileEntry
is the first entry of that array.
Simpler example (JavaScript):
const firstEl = ([el]) => el;
console.log(firstEl([a, b, c]));
Does it convert the fileEntry to an array? I f yes why that won't work?
No, it does the opposite. So the first line of your function is backwards. This is the equivalent of the first bit of code:
const onDrop = (fileEntry) => {
[fileEntry] = fileEntry
fileEntry && fileEntry.file(file => processFile(file))
}
Upvotes: 5