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:
...foocreates a new array, a copy of[1, 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,foobecomes a constant equal to thefooproperty inmyObj.
Questions
- What exactly is happening in the destructuring assignment?
- Could someone demonstrate the steps that occur above, without using destructuring?
- Is there a place in the ECMA spec (or similar) where the behavior is explained?
console.log({...[3,4]}). since arrrays are also object in js such that you can say that first key is 0 and so on. this is how i understood. also you can access arrays as if you would access an object. for example[3,4][0]would give 3 and{0:3,1:4}[0]would also give 3fozhas a length property but it doesn't. I guess that array has some special treatment in this scenario.