Loops can print out each item of the array. This works well in the console and with alert() as one follows the next. However when trying to write to the page, say using innerHTML each time the loop repeats the innerHTML is rewritten and the end result is that you see only the last result.
function listScientificFruit() {
const ul =document.querySelector('section>ul');
for (let i =0; i < scientificFruit.length; i++ ) {
ul.innerHTML +=`<li> ${scientificFruit[i]} </li>`;
}
};
The second part uses a for ... of loop.
function listFruit() {
const para =document.querySelector('section>p');
for (let frt of fruit) {
console.log(frt);
para.innerHTML +=`${frt}, `;
}
};
A different way
So a different way to use a loop is by attaching the array to the start of the for loop. So with an array called myArray it would be: myArray.forEach
When looping through arrays the newer for ... of loops are simpler to write than a regular for loop.
Remember that when using loops on things like .innerHTML to use += to avoid rewriting over the same thing each loop.
One issue with using += is that it outputs again and again every time you press the button. My fix for this is simply to clear anything in the HTML element by adding .innerHTML = '' at the start of function.
Looking stuff up online is probably better than trying to figure things out especially when there’s lots you don’t know, eg. +=.