I am having one very confusing issue that I don’t quite understand why…
In this two snippets below, they are supposed to produce the same results, as one uses arr.length and the other uses “3” instead.
Obviously, arr.length = 3, and I don’t understand why this two would produce two different results…
Any ideas why?
arr = ['A', 'B', 'A'];
arrR = [];
console.log(arr.length) // 3
for (let i = 0; i < arr.length; i++) {
let tmp = arr.pop();
arrR.push(tmp);
}
console.log(arr); // ["A"]
console.log(arrR); // ["A", "B"]
By replacing arr.length with 3 instead:
arr = ['A', 'B', 'A'];
arrR = [];
for (let i = 0; i < 3; i++) {
let tmp = arr.pop();
arrR.push(tmp);
}
console.log(arr); // []
console.log(arrR); // ["A", "B", "A"]
It’s very simple. Arrays are zero indexing. Starts with zero not one so in your second snippet if your replace 3 with 2 it will give you same results. However, length will remain 3 because it is counting 0 , 1 and 2.
If you add a console log inside the loop you will see what is going on:
arr = ['A', 'B', 'A'];
arrR = [];
console.log(arr.length) // 3
for (let i = 0; i < arr.length; i++) {
console.log('i=' + i + ', length=' + arr.length)
// i=0, length=3
// i=1, length=2
let tmp = arr.pop();
arrR.push(tmp);
}
console.log(arr); // ["A"]
console.log(arrR); // ["A", "B"]
The loop condition changes each time the loop goes round.
The loop condition is i < arr.length and gets reevaluated everytime the program goes around the loop. And each time it does, the array has got shorter, so it never makes it to the third element.
This is exactly right. In this case, the best solution might be to initialize a variable to the array length before the loop (so it’s a static value), and use that variable inside the loop condition.