1

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

asked Jun 19, 2021 at 4:31
1

2 Answers 2

5

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.

answered Jun 19, 2021 at 4:34
Sign up to request clarification or add additional context in comments.

1 Comment

Doh, don't tell anyone I asked this question.... Thanks for your answer. I will accept in 10 minutes when I can.
0

arr = [1,2,3];
i = arr.length - 1;
while (i > -1) {
 console.log(arr[i]);
 i--;
}

answered Jun 19, 2021 at 10:15

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.