zzgooloo zzgooloo - 4 months ago 10
Javascript Question

JavaScript Arrays and For loops

Can someone please tell me why the length of

secondArray
is 5 instead of 10?

my result looks like this after executing the code:


secondArray = 1,2,3,4,5,6,7,8,9,10

secondArray = 1,2,3,4,5


Why is this?

var firstArray = [];
var secondArray = [1,2,3,4,5,6,7,8,9,10];

document.write("secondArray = " + secondArray)

for(i = 0; i < secondArray.length; i++){
secondArray.pop();
}

document.write("<br/>"+ "secondArray = " + secondArray)

Answer

secondArray.length gets calculated for each iteration. On each iteration secondArray has one item less.

To pop() all the elements save secondArray.length and use the variable:

var firstArray = [];
var secondArray = [1,2,3,4,5,6,7,8,9,10];

document.write("secondArray = " + secondArray)

var len = secondArray.length;

for(i = 0; i < len;  i++){
    secondArray.pop(); 
}

document.write("<br/>"+ "secondArray = " + secondArray)

Note

There are many other and better ways to empty an array as OP aware of already. The answer addresses the common mistake of thinking that a for loop condition is calculated only at the first iteration.