Loops are useful when you want to execute the same code repeatedly, each time with a different value.
This is often the case when working with arrays.
text += cars[0] + “<br>”; text += cars[1] + “<br>”; text += cars[2] + “<br>”; text += cars[3] + “<br>”; text += cars[4] + “<br>”; text += cars[5] + “<br>”; |
for (let i = 0; i < cars.length; i++) { text += cars[i] + “<br>”; } |
JavaScript offers several types of loops: