for Loop in JavaScript

The for loop in JavaScript, is used to execute some block of code, multiple times. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <script>
      let num = 2;
      console.log("Multiplication Table of", num, "is:");
      for(let i=1; i<=10; i++)
      {
         console.log(num*i);
      }
   </script>
   
</body>
</html>

The snapshot given below shows the sample output produced by above JavaScript example on for loop:

javascript for loop

JavaScript for Loop Syntax

The syntax of for loop in JavaScript, is:

for(initializeStatement; conditionStatement; updateStatement) {
   // body of the loop
}

The initializeStatement executes at first and only for once.

Every time, before entering into the body of the loop, the conditionStatement must be evaluated as true.

The updateStatement executes every time before executing the conditionStatement, except for the first time.

JavaScript for Loop Example with Explanation

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <script>
      let x = 10;
      for(let i=0; i<5; i++)
         document.write(x, "<BR>");
   </script>
   
</body>
</html>

The sample output of above example is:

javascript for loop example

In above example, the execution of for loop goes like:

JavaScript for...in Loop

The JavaScript for...in loop is used to loop through the properties of specified object. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <script>
      const myarr = [10, 20, 30, 40, 50];
      for(let i in myarr)
      {
         console.log(myarr[i]);
      }
   </script>
   
</body>
</html>

The output should be:

for loop in javascript

JavaScript for...in Loop Syntax

The syntax of for...in loop in JavaScript, is:

for (key in object) {
   // body of the loop
}

Or

for (variable in array) {
   // body of the loop
}

JavaScript for...of Loop

The JavaScript for...of is used when we need to loop through the values of an iterable object. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <script>
      const ma = [10, 20, 30, 40, 50];
      for(let x of ma)
      {
         console.log(x);
      }
   </script>
   
</body>
</html>

The output of above example is shown in the snapshot given below:

for of loop javascript

JavaScript for...of Loop Syntax

The syntax of for...of loop in JavaScript, is:

for (variable of iterable) {
   // body of the loop
}

JavaScript for...of Loop Example

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <script>
      const mystr = "fresherearth"
      for(let x of mystr)
      {
         console.log(x);
      }
   </script>
   
</body>
</html>

The output of above JavaScript example should be:

for of loop example javascript

Note - The for...in loop deals with indexes, whereas the for...of loop deals directly with values of specified object.

JavaScript Online Test


« Previous Tutorial Next Tutorial »