While Loop through Array | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

While Loop through Array

I'm totally, totally lost (again) on this one. I've stared at it and gone through previous lessons and scoured internet forums for hours and cant find anything that works. Task: Modify the code to output all elements using a while loop, instead of the for loop. The Code: let cart = ['banana', 'apples', 'milk']; for(let x=0; x<3; x++){ console.log(cart[x]); } I need to change this to a while loop to output the same answer as the for loop. Not a clue. Anyone enlighten me? Many thanks

22nd Mar 2022, 9:29 PM
Thomas Murphy
2 Answers
+ 5
// try this let cart = ['banana', 'apples', 'milk']; let x=0; while(x<cart.length){ console.log(cart[x]); x++; }
22nd Mar 2022, 9:36 PM
SoloProg
SoloProg - avatar
+ 4
Some sick and twisted imp tapped this out on my keyboard. Nobody saw me do it. let cart = ["bananas", "apples", "milk"]; for( let x = 0; /*while (*/ x<3 /*) {*/; console.log(cart[x]), x++/*; }*/ ); Hmm, it really works.
23rd Mar 2022, 12:06 AM
Brian
Brian - avatar