# FOR loops in JavaScript

In 
Published 2022-12-03

This tutorial explains to you how you can use 'for' loops in JavaScript. The 'for' loop (statement) is very used in JavaScript.

There are 2 FOR loops in JavaScripts: FOR loop and FOR/IN loop :

# FOR loop in JavaScripts :

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
</head>

<body bgcolor="#E9F3C5">

<div id="parentDiv">   Information o parent div.
  <div id="childDiv1">   >>>>> Information on child div 1</div>

  <div id="childDiv2">   >>>>> Information on child div 2</div>
</div>

<script type="text/javascript">
 
      var i = 0;
      var parent = document.getElementById('parentDiv');
      var child = document.getElementById('childDiv2');
      var text = document.createTextNode("");
   
      for (i = 0; i < 5; i++) {
       
         if (i < 3) {
              text = document.createTextNode("FOR loop in JavaScript " +i+ " / ");
         } else if (i == 3) {
              text = document.createTextNode("For loop in JavaScript " +i+ " / ");
         } else {
              text = document.createTextNode("for loop in JavaScript " +i+ " / ");
         }
 
         parent.insertBefore(text, child); 
      };
 
    </script>

</body>
</html>

Here is the result of the code above:

# FOR/IN loop in JavaScripts :

<!DOCTYPE html>
<html>
<body bgcolor="#FFFFCC">
 
<h1>JavaScript FOR IN Loop</h1>
 
<p>The for/in statement loops through the properties of an object / array.</p>
 
<p id="test1"> </p>
<p id="test2"> </p>
<p id="test3"> </p>
<p id="test4"> </p>
<p id="test5"> </p>
<p id="test6"> </p>
 
<script>
   var result1 = ""; 
   var result2 = "";
   var result3 = "";
   var result4 = "";
   var result5 = "";
   var result6 = "";
    
   var person = {name:"John", job:"Analyst", age:25, email : "john_analyst@gmail.com"};
   var people = ["John", "Paul", "Andrew", "Samuel"];
    
   var people2 = [];
   people2[1] = "John";
   people2[2] = "Paul";
   people2[3] = "Andrew";
   people2[4] = "Samuel";
    
   var x;
   var y;
   var z;
    
   for (x in person) {    
      result1 = result1+ person[x] + " ";
      result2 = result2 + x + " ";
   }
 
   for (y of people) {
      result3 = result3+ people[y] + " ";
      result4 = result4 + y + " ";
   }   
    
    for (z of people2) {
      result5 = result5 + people2[z] + " ";
      result6 = result6 + z + " ";
   }  
    
   document.getElementById("test1").innerHTML = result1;
   document.getElementById("test2").innerHTML = result2;
   document.getElementById("test3").innerHTML = result3;
   document.getElementById("test4").innerHTML = result4;
   document.getElementById("test5").innerHTML = result5;
   document.getElementById("test6").innerHTML = result6;
          
</script>
 
</body>
</html>

Here is the result of the code above: