2

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?

1
  • 2
    Your code explicitly sets the .length of array1 to zero. Pushing the array into another array does not make a copy. Commented Aug 20, 2018 at 18:22

4 Answers 4

4

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.

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

Comments

1

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.

Comments

1

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.

1 Comment

Thank you so much, I actually wanted to know too how can get the desired result.
1

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);

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.