Why does this code work?

const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY'];
let arr2;

arr2 = [];  // Change this line

  for (let i = 0; i > -5; i--) {
    arr2.unshift(arr1.pop())
  }


console.log(arr2);

I just tried to use for loop instead of using spread operator. What I don’t understand is why is this code working as I haven’t assigned " i " to anything.

You’ve assigned 0 to i here:
let i = 0

You only need that variable to control the number of iterations of the loop, but you don’t need it in the loop’s body. Because .pop always removes the last item in an array, and .unshift pushes a new item to an array at position 0.

So, whenever you arr2.unshift(arr1.pop()), it takes whatever arr1.pop() returns (which is the last element in arr1) and unshifts it into arr2.

1 Like

if i am correctly getting what concerns you about the code:

as I haven’t assigned " i " to anything.

I think you meant that you haven’t used i inside the for loop, and you actually don’t need to because :

  • You have assigned i to 0 (i = 0),
  • You have given i an exit condition (i > -5),
  • You made i decrement by 1 with every iteration (i--).

So in this case, the line of code arr2.unshift(arr1.pop()); will be executed exactly five times because you told it to. this program cuts the last item from arr1 (arr1.pop()), assign it to the head of arr2 (arr2.unshift()) 5 consecutive times.

I think you’re a bit confusing for() {} with how do{} while() or how while(){} work. The latters -when working on arrays item by item- require that you include/use a counter (i for example) inside the loop body, and explicitly drop the exit condition in the while() part, unlike for () {} which iterates for a specific, finite and known (to the program at least) number of times.

I hope this helps, happy coding!

2 Likes

Thank you so much I understand it now.

Thanks for explaining it. Its really helpful.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.