Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Array referencing in constructor affected by push

I don’t understand why pushing to the array affects the result, while changing the array items does not.

How can this be written so that the restore method returns the initial array?

class Snapshot {
    constructor(array) {
        this.array = [...array];
    }

    restore() {
        return this.array;
    }
}

var array = [1, 2];
var snap = new Snapshot(array);

array[0] = 3;
array = snap.restore();
console.log(array.join()); // Logs "1,2"

array.push(4);
array = snap.restore();
console.log(array.join()); //It should log "1,2", but logs "1,2,4"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This line…

array = snap.restore();

assigns the object reference of snap.array to array so they are referring to the same object value. Manipulating array at this stage also manipulates snap.array.

If you want to break references and prevent external manipulation of class members, you want this instead

restore() {
  return [...this.array]
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading