javascriptreference

Variable references question


how come every time you make a change to one reference of a array it does not make a change on another either though both point to the same object.

Example:

myArray = new Array(5,5,5);
Array2 = new Array(7,7,7);
alert(myArray)  // still equals 5,5,5,`

Solution

  • [edit 12/2024] ... when a 13 year old answer comes to haunt you.

    Array is a native Object. From it, you can create instances, either by using the Array function, by instantiating using the new keyword or using an Array literal ([...]).

    So var myArr = new Array(5,5,5) creates an instance of Array. myArray is a reference to this instance.

    The variable myArr is a brand new instance of Array. It has nothing to do with myArray.

    When you create a copy of myArray, the copy will reference it's original and a change of one of the values of the copy will also change the value in the original.

    const myArray = new Array(1, 2, 3, 4);
    
    // create a copy:
    const copyOfMyArray = myArray;
    
    console.log(`myArray: [${myArray}], copyOfMyArray: [${copyOfMyArray}]`);
    
    // change a value in the copy:
    copyOfMyArray[0] = 42;
    
    // copyOfMyArray is a reference to myArray
    console.log(`myArray: [${myArray}], copyOfMyArray: [${copyOfMyArray}]`);
    
    // it works both ways
    myArray[1] = 42;
    console.log(`myArray: [${myArray}], copyOfMyArray: [${copyOfMyArray}]`);