Home > Software engineering >  Object Destructuring with Rest Parameter, on Array
Object Destructuring with Rest Parameter, on Array

Time:11-27

I have a decent handle on Rest, Spread, and Destructuring in Javascript.

Even so, I have been unable to figure out what exactly is happening in the following code:

const { ...foo } = [1, 2];
console.log(foo);

I have broken down the steps in my head, as follows:

  1. ...foo creates a new array, a copy of [1, 2]
  2. The object destructuring should, to my understanding, unpack an object on the right-hand-side, and place it into new variable(s). This is where I fall off. Above, the code behaves such that an array from the right-hand-side is seen as an object, and a new object is created with each property equal to each element of the array. That does not happen in a destructuring assignment without rest: const { foo } = myObj; <-- No new object is created here, foo becomes a constant equal to the foo property in myObj.

Questions


  1. What exactly is happening in the destructuring assignment?
  2. Could someone demonstrate the steps that occur above, without using destructuring?
  3. Is there a place in the ECMA spec (or similar) where the behavior is explained?

CodePudding user response:

What exactly is happening in the destructuring assignment?

A destructuring assignment where the left side has [ ...rest] notation will create an array for rest. When it has { ...rest} notation, it will create a plain object for rest.

In the first case, the array values from the right hand side are iterated, and these populate the left hand array.

In the second case, the object entries from the right hand side are iterated, and these define the key/value pairs of the left hand object.

Could someone demonstrate the steps that occur above, without using destructuring?

Like this:

let foo = {};
for (const pair of [1, 2].entries()) {
    foo[pair[0]] = pair[1];
}

console.log(foo);

Is there a place in the ECMA spec (or similar) where the behavior is explained?

The ECMA Script reference is at Destructuring Assignment, and the ObjectAssignmentPattern with AssignmentRestProperty. In that section you'll find Runtime Semantics: RestDestructuringAssignmentEvaluation.

There you see a plain object is created (in step 2). In step three the procedure CopyDataProperties ( target, source, excludedItems ) is executed. This copies enumerable (see step 4.c.ii) properties of the source object (in your case an array object) into the target object.

It is important to stress that only own, enumerable properties are included, which explains why for instance the length property is not copied into the target object.

CodePudding user response:

We can think of an array as a map with the index being the key. In that way the output is explainable:

const { ...foo } = [1, 2];
console.log(foo);

has the same behavior as:

const { ...foo } = { 0: 1, 1: 2 };
console.log(foo);

  • Related