Darrell Brogdon
Darrell Brogdon

Reputation: 6973

What does this use of the spread operator do?

I just noticed this in some code and I've been trying to understand what it is doing.

this.rows[rowIndex][cell] = event.target.value;
this.rows = [...this.rows];

It appears to me that it's simply assigning this.rows to itself. Is there some other use of the spread operator in which this makes sense? Or is it simply a bug?

Upvotes: 1

Views: 78

Answers (1)

trincot
trincot

Reputation: 350147

The spread syntax will give a shallow copy of the original array.

There are at least two reasons why this may be useful:

  • Any references that exist to the original rows property will not be affected by later assignments made to the direct properties of the copied array.
  • If the original value of rows was not a true array, but iterable (array-like), then the result of the spread syntax assignment will still be a true array.

Here is an artificially made object to illustrate these two points:

class Foo {
    constructor(n) { // Define array-like object 
        this.rows = {
            // Define iterator
            [Symbol.iterator]: function* () {
                for (let i = 0; i < n; i++) yield this[i];
            },
        }
        // Create "index" properties
        for (let i = 0; i < n; i++) this.rows[i] = [];
    }
    bar(rowIndex, cell, value) {
        this.rows[rowIndex][cell] = value;
        console.log(this.rows);
        // Take shallow copy
        this.rows = [...this.rows];
        // Now it is a true array
        console.log(this.rows);
        // We add a value to that array, which other copies will not see
        this.rows.push("added");
        console.log(this.rows);
    }
}
var foo = new Foo(2); // Create array-like object
var remember = foo.rows; // get its rows
foo.bar(1, 0, 15); // set one particular value to 15
// Demonstrate that the value that was added inside the method is not in our copy
console.log(remember);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Note how the first output has the { } notation: it is not recognised as a true array. The second output is with [ ]: a true array. The third output shows an additional value that was pushed on that array. The final output shows these manipulations (making it an array and adding a value to it) are not reflected in the original reference we had to the rows property.

Upvotes: 1

Related Questions