how to fix this error: In the for loop, one of the three conditions is incorrect and will cause the code to execute forever. Cha | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

how to fix this error: In the for loop, one of the three conditions is incorrect and will cause the code to execute forever. Cha

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] + '.'); }

17th Dec 2017, 12:02 AM
Patrick Estaron Magayon
Patrick Estaron Magayon - avatar
3 Answers
+ 14
replace thingsToDoIndex++ with thingsToDoIndex--
17th Dec 2017, 12:05 AM
Kamil
Kamil - avatar
+ 1
Because you start at thingsToDo.length -1 (positive nunber), as long as thingsToDoIndex >=0 and you use ++, it will never get to 0. p.s. You can also start at 0, and try to reach thingsToDo.length -1.
17th Dec 2017, 3:34 AM
Amir Galanty
Amir Galanty - avatar
- 1
Question: why go backwards instead of forwards?
17th Dec 2017, 1:42 AM
H Chiang