Skip to content
Advertisement

Why does while(arr.length) behave this way

I have the code

let arr = [1, 2, 3];

while (arr.length) {
  console.log(arr[arr.length - 1]);
  arr.pop();
}

the output for this code is

3
2
1
1

but I expected

3
2
1

when I switch the code to

let arr = [1, 2, 3];

while (arr.length) {
  console.log(arr[arr.length - 1]);
  arr.pop();
}
console.log();

I get

3
2
1

Why does it behave this way? Why am I getting a duplicate in the first code example? How can I prevent this? Thanks

Advertisement

Answer

Just run the script anywhere else other than in the browser console and it’ll behave normally.

let arr = [1, 2, 3];

while (arr.length) {
  console.log(arr[arr.length - 1]);
  arr.pop();
}

For example, on a webpage, the code would work just fine.

In the console, the final expression in the block is the completion value of the block. Here, that’s the final value popped, which is 1. So 1 is the completion value of the while loop, which browsers will then log for you when the while loop is the final block in the code.

You could also just ignore the completion value of the code, and only look at what gets logged by the code itself, eg

enter image description here

which is a perfectly reasonable approach.

Advertisement