javascriptarraysdestructuringobject-destructuringrest-parameters

JavaScript: Is a new array created by a rest element in destructuring assignment?


I'm wondering if array destructuring syntax that uses a rest element (be it an object or array) creates a new array in memory that is then used by that nested rest element's destructuring assignment? In other words, I'm wondering if syntax like:

let [a, b, ...[c, d]] = [1, 2, 3, 4];`

results in a new array being created after a and b are initialized for the ...[c , d] destructuring to then use?

I ask as MDN on their page about Destructuring Assignment in their section on "Using a binding pattern as the rest property" states:

The rest property of array destructuring assignment can be another array or object binding pattern. The inner destructuring destructures from the array created after collecting the rest elements, so you cannot access any properties present on the original iterable in this way.

This is in regards to such an example as I gave above. The last sentence states "from the array created after collecting the rest elements", which seems to indicate an entirely new array is thus being created for that destructuring?

My main curiosity in regards to this is about performance. Creating a new array (or iterable) seems slow, and so I'm wondering if this is implemented or specified another way? I have read the specification (linked under "Specification" on the above MDN page), but still have this question. I have also done a performance test using JSBench.me which seems to state that using the destructuring syntax as opposed to not (for instance, my above example as opposed to just

let [a, b, c, d] = [1, 2, 3, 4];

) is over 90% slower.


Solution

  • Yes, rest syntax in destructuring is specified to create an array. If you are immediately destructuring it again, it is not observable by your code, so an engine could in theory optimise away the intermediate allocation without changing the behaviour of the code. However, such an unusual pattern is unlikely to be optimised for, it would not occur in good idiomatic code.