2

An example of below is available here: http://jsfiddle.net/valgaze/se9bmx7t/

Big question: Why does clearing an array "break" the relationship between an array and that array's reference in an object literal in Javascript?

Imagine we have an array stored in a variable and we have object literal with a reference to that array as one of the properties of the object. When we use any of the typical array methods (push, pop, shift, etc) on the array, the object literal gets updated with the result. And similarly if we update the array by accessing it from the object literal then the array variable is updated.

Ex. Updating the object updates the array (and vice versa)

var myArray = ["item1", "item2", "item3"];

var myObject = {key1:"value1", key2:myArray}

//Array is updated, so object is updated
myArray.push("item4"); //Update the array

console.log(myObject.key2); //Object's array updated with new pushed value

//Object is updated, so array is updated
myObject.key2.push("item5"); //myArray is updated with the item5
console.log(myArray); //Array updated with item5

Question: Why does "clearing" the array break the binding/coupling on the array reference in the object?

    //[...] continued from first block above

    myArray = ["muahahah, everything is wiped out"];
    console.log("myArray", myArray); //Returns ["muahahah, everything is wiped out"]
    console.log("myObject.key2", myObject.key2); //Returns the original items 1-5 

    //If we clear out the array via the object, the array does get updated
    myObject.key2 = ["cleared the array from object"];
    console.log("myArray", myArray); //returns ["cleared array"]
    console.log("myObject.key2", myObject.key2); //returns ["cleared array"]

There must be something going on with manipulating an array like this: myArray = ["wiped values"];

2

1 Answer 1

1

You're not "clearing" the array, you're assigning a new value to your variable. The original array still exists (as a reference inside the other object), but now myArray points to a different array reference.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.