The for loop in JavaScript
The for loop is used to execute the given code to the given number of times in JavaScript.
for (let x = 0; x < 10; x++) { if (x === 3) { break; // exit the loop when x = 3 } console.log(x); } // Output: 0, 1, 2
Structure of for loop
This is how the for loop is used, generally, in JavaScript:
for ( initialization_operator; condition; counter_update){ //Place code here to execute; }
There:
Part | Description |
initialization operator | After the ‘for’ keyword, you may specify the initialization operator, for example, a variable’s initial value.
This is the part of the for loop that executes first, however, this is optional. |
condition | After that, the condition is given that evaluates in each iteration.
Until the condition is true, the code will keep on executing inside the curly braces. |
update counter | The last part in the parenthesis is the update counter.
This may be an increment or decrement operator. |
See the following examples of using the JavaScript for loop where I will start with simple examples and then use them in JS arrays with its length property.
An example of displaying numbers in a div by using a JS for loop
- In this example, a variable is assigned an initial value of 1.
- The condition is to keep on iterating till the variable value is 10.
- In each iteration, the variable value is incremented by 1.
HTML and JavaScript:
<!DOCTYPE html> <html> <head> <style> .divclass { background: #3B505F; height: auto; width:350px; border-radius: 15px; padding:20px; font-size:16px; color:#fff; } </style> </head> <body> <h3>A for loop demo</h3> <div class="divclass" id="fordemo"></div> <script type="text/javascript"> var x; var display_for = "The output of for loop <br>"; for (x=1; x <= 10; x++){ display_for += x + "<BR>"; } document.getElementById("fordemo").innerHTML = display_for; </script> </body> </html>
Output:
In the <script> section of code, just above the </body> tag, this is how the for loop is used:
for (x=1; x <= 10; x++){ display_for += x + "<BR>"; } document.getElementById("fordemo").innerHTML = display_for;
In the above case:
- The initialization is: x=1;
- The condition is: x<=10;
- The update/increment is: x++
Inside the curly braces, the value of ‘x’ for each iteration is gathered till it reaches 11 where the condition becomes false.
As the condition becomes false, the control will be shifted outside of the for loop. The next line outside of the for loop will display the gathered values into a <div> tag of HTML.
An example of decrement operator
In this example, instead of using an increment operator, a decrement operator is used.
The initial value of the variable is set as 10 and it will decrease with each iteration by one.
code:
<body> <h3>A for loop demo</h3> <div class="divclass" id="fordemo"></div> <script type="text/javascript"> var x; var display_for = "The output of for loop with decrement operator<br>"; for (x=10; x >= 1; x--){ display_for += x + "<BR>"; } document.getElementById("fordemo").innerHTML = display_for; </script> </body>
Output:
An example of increasing by more than one
In the above two examples, the increment or decrement operator was given the value of 1 by using the ‘++’ or ‘- -‘.
You may specify higher or lower numbers.
See the following example, where I updated the counter as the last line in the for loop rather than using in the parenthesis:
for (x=10; x <= 100; ){ display_for += x + "<BR>"; x = x + 10; } document.getElementById("fordemo").innerHTML = display_for;
Output:
Similarly, you may decrease the value in each iteration.
Using for loop in arrays of JavaScript
The for loop is particularly useful in the arrays of JavaScript.
The for loop of JavaScript enables it to iterate through the array elements quite easily.
- In the following examples, I will show you how to display numeric array elements as well as strings by using the for loop.
- In the first example, a numeric array of five elements is created.
- After that, a JavaScript for loop is used to iterate through the array element where the length property of the array is used.
HTML and JavaScript:
<!DOCTYPE html> <html> <style> #div_demo { background: #4C9B79; height: 220px; width:40%; border-radius: 15px; padding:20px; font-size:18px; color:#fff; } </style> <head> </head> <body> <div id="div_demo"></div> <script type="text/javascript"> var Arrnum = [5,10,15,20,25]; var num; var displayArray = "Displaying array elements by for loop: <BR>"; for (num=0; num < Arrnum.length; num++){ displayArray += Arrnum[num] + "<BR>"; } document.getElementById("div_demo").innerHTML = displayArray; </script> </body> </html>
Output:
In the for loop, the initialization and increment operators are the same as those used in the first example. However, to specify the condition, the length property of arrays is used.
So the condition becomes; execute the for loop to the total number of elements in the given array. This is how the for loop is used in the example:
var Arrnum = [5,10,15,20,25]; var num; var displayArray = "Displaying array elements by for loop: <BR>"; for (num=0; num < Arrnum.length; num++){ displayArray += Arrnum[num] + "<BR>"; } document.getElementById("div_demo").innerHTML = displayArray;
The variable is used to specify the current element and assign its value to another variable, displayArray. The displayArray variable collects the element values and finally, this line displays the array elements in a div:
An example of using the string array in for loop
This time, an array of strings is created and its elements are displayed by using a for loop. Although, there is no difference in creating a numeric or string array. Also, the way a for loop is used is the same.
This is how the array is created and displayed by using the for loop:
<script type="text/javascript"> var ArrNames = ["Mike", "Lubna", "Mika", "Michalle"]; var num; var displayArray = "Displaying array elements by for loop: <BR><BR>"; for (num=0; num < ArrNames.length; num++){ displayArray += ArrNames[num] + "<BR>"; } document.getElementById("div_demo").innerHTML = displayArray; </script>
Output:
An example of using variables as range in for loop
In the above example, I used fixed numbers to execute the for loop by specifying a number in the condition. For example:
x <= 10;
x <= 100;
x >=1;
In this example, as the demo page loads, you can see a drop-down for selecting the number of elements for creating an array. After selecting the number, the lower div will show the array of elements created on the fly.
First, have a look at the demo (copy/paste in your editor and execute the code) and then I will explain how for loop is used in that example:
Complete Code:
<!doctype html> <html> <head> <style> #arr_demo { background: #5BB75B; height: auto; width:220px; border-radius: 15px; padding:20px; font-size:20px; color:#000; } .divcls{ background: #6A0432; width:220px; border-radius: 15px; padding:20px; font-size:18px; color:#fff; } </style> </head> <body> <div class="divcls"> <label>Select number of Elements and For loop will execute</label><select id="dynarrayelements" onChange="dynFunction()"> <option>Create Array elements</option> <option value="5">5</option> <option value="10">10</option> <option value="15">15</option> <option value="50">50</option> <option value="150">150</option> <option value="200">200</option> </select> </div> <p id="arr_demo"> </p> <script> function dynFunction() { var dynarray = []; var createDynArr = (document.getElementById("dynarrayelements").value); var j= 10; // Used to give values to array elements var num; var displayArray = "The Dynamic array of " +createDynArr + " by using for loop! <BR><BR>"; //Creating a Dynamic array for (var i = 0; i < createDynArr; i++) { //dynarray.unshift(j); dynarray[i] = [j]; j = j + 10; } //Displaying the dynamic array in a Div element for (num=0; num < dynarray.length; num++){ displayArray += dynarray[num] + "<BR>"; } document.getElementById("arr_demo").innerHTML = displayArray; } </script> </body> </html>
Sample output as I selected 10:
This is how it worked
On the onChange event of the HTML select dropdown, a JS function is called.
Inside the function, the selected number is used in the for loop to create array elements.
//Creating a Dynamic array for (var i = 0; i < createDynArr; i++) { //dynarray.unshift(j); dynarray[i] = [j]; j = j + 10; }
After creating the array, another for loop is used to display the elements:
//Displaying the dynamic array in a Div element for (num=0; num < dynarray.length; num++){ displayArray += dynarray[num] + "<BR>"; } document.getElementById("arr_demo").innerHTML = displayArray; }