I was toying with for … loops, bumped into something weird
function turnaround (arr) {
var nwarr = [];
// console.log(arr.length);
for (var i = 0; i < arr.length; i++){
// console.log(i);
var out = arr.pop();
nwarr.push(out);
}
return nwarr;
}
turnaround ([1,2,3,4,5,6,7,8,9]); // Array(5) [ 9, 8, 7, 6, 5 ]
Huh? The output? Array only 5?
However:
changed it into ’ for (var i = 0; i < 9; i++) and then the array was completed: // Array(9) [ 9, 8, 7, 6, 5, 4, 3, 2, 1 ]
So:
With ‘i < arr.length’ my loop goes only 5 x, output Array(5) [ 9, 8, 7, 6, 5 ]
However ‘arr.length = 9’, as checked and confirmed by ‘console.log(arr.length);’
I changed ‘i < arr.length’ into ‘i < 9’, and the loop completes neatly after 9 x.
I changed back into ‘i < arr.length’ and again the loop stops after 5 x.
Anyone understanding this?
Yes, I see what you mean. It took me a little bit of thinking to figure it out. The problem is that the pop() method, changes the array (arr) in place. This means that on the line after var out = arr.pop();, the length of arr is no longer 9 but 8 (on the first pass), and every time you loop over the array the length gets smaller by one!
Hi John, I am not sure if i understand you correctly. Do you mean it ‘halts’ too early because arr is empty. too early? I put a console.log directly after var out = arr.pop() and apparently the loop ‘halts’ when arr still has five elements.
function turnaround (arr) {
var nwarr = ;
// console.log(arr.length);
for (var i = 0; i < arr.length; i++){
// console.log(i);
var out = arr.pop();
console.log(arr.length);
nwarr.push(out);
}
return nwarr;
}
turnaround ([1,2,3,4,5,6,7,8,9]);
// output console.log(arr.length) is:
8
7
6
5
4
Array(5) [ 9, 8, 7, 6, 5 ]
Yes, it’s true that the loop halts. It halts because the condition i < arr.length is no longer true. This is because every time the arr.pop() executes, that length keeps getting smaller.
To make it more clear, in the console.log(arr.length) you added, add the value of i like this to see what’s happening more clearly:
console.log(i, arr.length);
What you’ll see is that both numbers keep getting closer to each other. i keeps rising, and arr.length keeps lowering, until i = arr.length, in which case it exits the loop because the condition i < arr.length is no longer true.
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.