Console.log shows same thing twice in while loop


#1

I don’t understand why this code displays “I have to many things to do!” twice.

I also don’t understand how the length of the list is 3 when there are 5 items in the list.



let thingsToDo = ['do laundry', 'take out the garbage', 'make dinner', 'walk the dog', 'go to the bank'];

for (let thingsToDoIndex = thingsToDo.length - 1; thingsToDoIndex >= 0; thingsToDoIndex--) {
  console.log('I need to ' + thingsToDo[thingsToDoIndex] + '.');
}

 while (thingsToDo.length > 3) {
   
   thingsToDo.pop();
   console.log('I have too many things to do!');
 }

console.log(thingsToDo.length);



#2

Hi there,
See that length of the array is 5 in the starting.
Then when while loop runs for first time it is reduced to 4 as you are replacing the last element of the array with nothing. This is in fact deleting the last element.
Then loop runs for the second time as still length of array is greater than 3. Then it gets reduced to 3 so loop can’t run for the third time. As loop runs twice your statement gets logged to console twice.
And similarly the length of array becomes three at last. Therefore the console shows 3 when you log the length of the array to it.

I Hope that you understand.


#3

Your code looks good @alenart the for loop should execute 5 times for each array element with a console.log statement

for (let thingsToDoIndex = thingsToDo.length - 1; thingsToDoIndex >= 0; thingsToDoIndex--) {
  console.log('I need to ' + thingsToDo[thingsToDoIndex] + '.');
}

the while loop iterates only 2 times because the conditional asks the length of the array content stays above 3
while (thingsToDo.length > 3){}

so it removes an element and logs a string 2 times from the array contents of thingsToDo

{
   thingsToDo.pop();
   console.log('I have too many things to do!');
}

and the last line shows the final length of thingsToDo
console.log(thingsToDo.length);


#4

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