3 Example(s) of Javascript For Loop


Description :

In this example, We will learn how to use JavaScript for loop, starting the counter from 0 and till less than 10, it will print "I am 0---9" See the code snippet:


Javascript For Loop Example - 1
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>   
<body>
  <script>
    var count;
    document.write("Starting Loop" + "<br />");
         
    for(count = 0; count < 10; count++){
    document.write("I am : " + count );
    document.write("<br />");
    }

    document.write("Loop stopped!");
         
      </script>
</body>
</html>

Output

Description :

In this example, We have an array of vehicles and implement the for loop on all vehicles. See the code snippet:


Javascript For Loop Example - 2
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>   
<body>
    <p id="sample"></p>
 <script>
var vehicles = ["Alto", "Zen", "Audi", "Cruze"];
var i, length, text;
for (i = 0, length = vehicles.length, text = ""; i < length; i++) {
    text += vehicles[i] + "<br>";
}
document.getElementById("sample").innerHTML = text;
</script>
</body>
</html>

Output

Description :

A new way to use JavaScript for loop 

var i = 0;

var length = vehicles.length;var text = "";for (; i < length; ){ text += vehicles[i] + " "; i++; }



Javascript For Loop Example - 3
<!DOCTYPE html>
<html>
<head>
<title>Welcome to LearnKode - A code learning platform</title>
</head>   
<body>
  <p id="demo"></p>
<script>
var vehicles= ["Alto", "Zen", "Audi", "Swift"];
var i = 0;
var length = vehicles.length;
var text = "";
for (; i < length; ) {
    text += vehicles[i] + "<br>";
    i++;
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

Output