Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JS Loop For

JavaScript Loops

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.

Instead of writing:

text += cars[0] + “<br>”;
text += cars[1] + “<br>”;
text += cars[2] + “<br>”;
text += cars[3] + “<br>”;
text += cars[4] + “<br>”;
text += cars[5] + “<br>”;

You can write:

for (let i = 0; i < cars.length; i++) {
  text += cars[i] + “<br>”;
}

Different Kinds of Loops

JavaScript offers several types of loops:

  • for: loops through a block of code a specified number of times.
  • for/in: iterates over the properties of an object.
  • for/of: loops through the values of an iterable object.
  • while: executes a block of code as long as a specified condition is true.
  • do/while: also runs a block of code while a specified condition is true, but guarantees at least one execution.