What’s the mechanism that makes destructuring & rest parameter create an isolated copy, while rest parameter expose the original array to mutation?

What’s the mechanism that makes destructuring & rest parameter create an isolated copy, while rest parameter expose the original array to mutation?
javascript
Ethan Jackson
function t(..._a) { console.log("t says:", _a[0] === a); // Output: t says: true } function v([..._a]) { console.log("v says:", _a === a); // Output: v says: false } const a = [{}, {}, {}]; t(a); v(a);

What’s the exact mechanism, at memory level, that makes destructuring "[..._a]" create an isolated copy, while rest parameters "..._a" expose the original array to mutation?

why isn't "[..._a]" equal to "_a[0]"?

Answer

In this case:

function t(..._a)

The _a variable is the array of all arguments passed to the function. What arguments were passed to the function?:

t(a);

One argument, and that argument is an array. So _a is an array containing exactly one element, and that element is the array referenced by a. So _a[0] and a refer to the same thing.

In this case:

function v([..._a])

The _a variable is an array which was created by destructuring whatever one argument is passed to the function. What is that argument?:

v(a);

It's the array that a references. So _a is a new array populated with the elements from the array a.

There's no different mechanism at play here, your examples are simply doing two different things. In the first example you wrap the original array in a new array, resulting in an array of arrays. In the second example you create a new array from the elements of the original array, resulting in a duplicated array.

Related Articles