Dany D
Dany D

Reputation: 1189

JavaScript object property gets modified in a very interesting way

I have put together a small test, can someone explain why does JavaScript do the following?

Why will testArr inherit the modifications of newArray?

var TestClass = function() {

            this.testArr = [10,11];

            this.addToArray = function() {
                var newArray = this.testArr;
                newArray.push(12);
            }
        }

        var testClass = new TestClass();

        testClass.addToArray();

        console.log(testClass.testArr); // will be [10, 11, 12]

Upvotes: 1

Views: 70

Answers (2)

David Snabel
David Snabel

Reputation: 10079

With following statement

var newArray = this.testArr;

You will not copy the values from inside testArr. You will create a reference to this array. When you make an adjustment to a reference you will automatically change the referenced source too.

When you want to copy the values from testArr to another variable you can do this instead.

var newArray = this.testArr.slice();

This will copy the values from testArr inside newArray.

Upvotes: 0

user229044
user229044

Reputation: 239270

Because they're the same array. Variables contain references to arrays. You're assigning that reference to a new variable, and now both variables point to the same array.

Here's a much simpler test which reproduces the behavior:

x = [1, 2]     // the value of x is a reference to an array
y = x          // the value of y is a reference to the same array
y.push(3)      // modify the array pointed to by both variables
console.log(x) // [1, 2, 3]

If you want to create a new array, you need to clone the array.

Upvotes: 8

Related Questions