Karan Singh Dhir
Karan Singh Dhir

Reputation: 751

Why does the array push an empty array into another?

Why is the value of array2 [[], [], [], [], []] at the end of the loop?

var array1 = [];
var array2 = [];

for (let i = 1; i <= 10; i++) {
  array1.push(i);
  if (i % 2 === 0) {
    //console.log(array1);
    array2.push(array1);
    array1.length = 0;
  };
};
console.log(array1);
console.log(array2);

Can anyone explain, what's going on in this code?

Upvotes: 2

Views: 1143

Answers (4)

Jose Mato
Jose Mato

Reputation: 2799

Because when you push an array / object variable, you are storing the reference, not the value. Making array1 length equals to 0 as you know you are deleting array1 values, and this cause the result you are seeing for array2.

If you want to have the behaviour you expect you can create a new array before each push like:

var array1 = [];
var array2 = [];

for (let i = 1; i <= 10; i++) {
  array1.push(i);
  if (i % 2 === 0) {
    array2.push(Array.from(array1));
    array1.length = 0;
  };
};
// []
console.log(array1);
// [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ], [ 9, 10 ] ]
console.log(array2);

Upvotes: 1

connexo
connexo

Reputation: 56773

The other answers have already explained what's going on, here's what to do to get what you expected:

var array1 = [];
var array2 = [];

for (let i = 1; i <= 10; i++) {
  array1.push(i);
  if (i % 2 === 0) {
    //console.log(array1);
    array2.push([...array1]);
    array1.length = 0;
  };
};
console.log(array1);
console.log(array2);

You can simply use a new ECMAScript feature called array destructuring [...arr] (destructuring into a new array), which creates a shallow copy of the array it is applied on.

Upvotes: 1

Sushanth --
Sushanth --

Reputation: 55750

It is because of array1.length = 0;.

You are pointing the same array reference and setting it to empty.

So technically you are pushing a new empty array for every even number in the iteration.

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190976

Arrays in JavaScript are mutable structures. array1 is getting emptied out each time by assigning 0 to length. Theres only 5 even numbers between 1 and 10 (namely: 2, 4, 6, 8, 10), so array2 has 5 references to array1 in it.

Upvotes: 4

Related Questions