1

The following code example is what i found here on the internet

arr[1].push('native', 'laravel');

with a description of

Here we use the javascript array push method to add two new elements(items) to the inner sub-array.

which was exactly what i wanted to accomplish!

But when i tried it several times by my self it always went like this:

let mainArr = [];

console.log("mainArr: ", mainArr);
// Working as expected: created an empty array

let emptyArr = [];

console.log("emptyArr: ", emptyArr);
// Working as expected: created an empty array

for (i = 0; i < 3; i++) {

  mainArr.push(emptyArr);
}

console.log("mainArr: ", mainArr);
// Working as expected: pushed 3 times the "emptyArr" into "mainArr"

let newArr = [["X"], [90]];

  mainArr[0].push(newArr);
  
console.log("mainArr[0]: ", mainArr[0]);
console.log("mainArr[1]: ", mainArr[1]);
console.log("mainArr[2]: ", mainArr[2]);
// NOT working as expected: pushed "newArr" into every of the three arrays within the "mainArr" !!!
// How can I solve this?

Would love to hear some tips :)

Thanks!

leonnicklas
  • 381
  • 1
  • 5
  • 20

1 Answers1

2

That's because arrays are objects in JS, ie non-primitive type of variables.

Long explanation

Javascript has 5 data types that are passed by value: Boolean, String, Number, null and undefined. These are called primitive types.

And it has 3 data types that are passed by reference: Array, Function, and Object. These are all technically Objects.

When you assign a non-primitive value to a variable what happens is that a reference of that value is assigned, not the actual value. Ie, that reference points to the object’s location in memory. The variables don’t actually contain the value.

In your case

When you push emptyArr 3 times you don't insert the value (ie. a new empty array) you insert the same memory reference of emptyArr. These 3 references point to the same location in memory that has that value of an empty array. Given that, now you insert newArr to the referenced value of the mainArr[0], but the rest elements mainArr[1], mainArr[2] are references that point to the same value as the one pointed by mainArr[0].

Hope it makes sense.

Otherwise, You can refer here https://stackoverflow.com/a/430958/4700560 or I also find this article very visually descriptive and helpful https://blog.penjee.com/passing-by-value-vs-by-reference-java-graphical

NikoKyriakid
  • 610
  • 7
  • 14