JavaScript Loop For of
JavaScript Basics

JavaScript Loop For of

JavaScript Loops

Loops are useful for executing the same code repeatedly with different values. This is especially helpful when working with arrays.

Example without a Loop:

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

Example with a Loop:

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

Different Kinds of Loops

JavaScript supports various types of loops:

  • for: Loops through a block of code a specified number of times.
  • for/in: Loops through the properties of an object.
  • for/of: Loops through the values of an iterable object.
  • while: Loops through a block of code as long as a specified condition is true.
  • do/while: Also loops through a block of code as long as a specified condition is true.

The For Loop

The for statement creates a loop with three optional expressions:

for (expression 1; expression 2; expression 3) {  // code block to be executed}
  • Expression 1: Executes once before the loop starts.
  • Expression 2: Defines the condition for running the loop.
  • Expression 3: Executes after each iteration of the loop.

Example :

for (let i = 0; i < 3; i++) {  text += "The number is " + i + "<br>";}

Explanation:

  • Expression 1 initializes the loop variable (let i = 0).
  • Expression 2 sets the loop condition (i < 3).
  • Expression 3 increments the loop variable (i++).

Expression 1

Usually used to initialize the loop variable.

Example
for (let i = 0, len = cars.length, text = ""; i < len; i++) {  text += cars[i] + "<br>";}

You can also omit Expression 1 if the variable is already initialized:

Example
let i = 1;let len = cars.length;let text = "";for (; i < len; i++) {  text += cars[i] + "<br>";}

Expression 2

Defines the condition for the loop to run.

Example without Expression 2 (using break)
let i = 0;for (; ;) {  if (i >= 3) break;  text += "The number is " + i + "<br>";  i++;}

Expression 3

Usually used to increment the loop variable.

Example with Custom Increment
for (let i = 0; i < 10; i += 2) {  text += "The number is " + i + "<br>";}‍

You can also omit Expression 3 and manage the increment inside the loop:

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

Loop Scope

Using var in a loop:

Example
var i = 5;for (var i = 0; i < 10; i++) {  // some code}// Here, i is 10‍Using let in a loop:
Example
let i = 5;for (let i = 0; i < 10; i++) {  // some code}// Here, i is still 5

In the first example, var redeclares the variable outside the loop. In the second example, let keeps the variable scope within the loop.

For/Of and For/In Loops

The for/in loop and the for/of loop will be explained in the next chapter.

While Loops

The while loop and the do/while loop will be explained in the upcoming chapters.

Take a look into your desired course