Search code examples
javascriptarraysdestructuring

Array destructuring via spread operator


The MDN documentation concerning array destructuring is pretty self-explanatory, however, I fail to understand what is happening behind the scenes when destructuring an array like so:

let Arr = [1, 3, 5, 6];
let newArr = [];

[newArr[0], ...newArr] = Arr;

console.log(Arr); // returns [1, 3, 5, 6]
console.log(newArr); // returns [3, 5, 6]

How is it that newArr does not inherit the first array member of Arr?


Solution

  • If you had

    [x, ...y] = Arr;
    

    it would be like

    x = Arr[0];
    y = Arr.slice(1);
    

    so when you have

    [newArr[0], ...newArr] = Arr;
    

    it’s like

    newArr[0] = Arr[0];
    newArr = Arr.slice(1);
    

    The assignments involved in destructuring happen left to right. Live:

    const listener = {
      get foo() {
        return {
          set bar(value) {
            console.log('setting bar');
          },
        };
      },
      set foo(value) {
        console.log('setting foo');
      },
    };
    
    [listener.foo.bar, ...listener.foo] = [1, 2, 3];