JavaScript For Loop Tutorial

JavaScript Loops

Loops can execute a block of code a number of times. if you want to run the same code over and over again, each time with a different value.

Instead of writing:

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

You can write:

for (i = 0; i     text +=bikes[i] + “
“;
}

JavaScript supports different kinds of loops:

  • for 
  • for/in 
  • while 
  • do/while 

The For Loop In JavaScript

The for loop is often the tool you will use when you want to create a loop.

Syntax: for(initializer; condition; iteration) { // Code to be executed }

The for loop requires the following three parts.

  • Initializer: Initialize a counter variable to start with
  • Condition: specify a condition that must be evaluated to be true for the next iteration
  • Iteration: increase or decrease the counter

The For/In Loop In JavaScript

The JavaScript for/in statement loops through the properties of an object:

Example

var person = {fname:”John”, lname:”Doe”, age:25}; 

var text = “”;
var x;
for (x in person) {
    text += person[x];
}

Take Your Free Live Demo Class Now

Enter Your DETAILS BELOW

To Get Complete Information or We Will Call You

We Will Send You the Course Fees Details In Below Number

Enter Your DETAILS BELOW

We Will Call Back You Shortly

Enter Your DETAILS BELOW

We Will Call Back You Shortly

Enter Your DETAILS BELOW

Enter Your DETAILS BELOW TO take

free demo class