The for loop in JavaScript
The for loop is used to execute the given code to the given number of times in JavaScript.
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; }
- After the for keyword, you may specify the initialization operator, for example, a variable’s initial value. This is the part of for loop that executes first, however this is optional.
- 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.
- 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 a simple example to using in JS arrays with its 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 the till the variable value is 10. While in each iteration, the variable value is incremented by one. See the demo online by clicking the link or image below:
See online demo and code
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 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 condition becomes false.
As the condition becomes false, the control will be shifted outside of the for loop. The next line outside of for loop will display the gathered values into a <div> tag of HTML.
An example with 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.
See online demo and code
This is how the for loop is used in that example:
for (x=10; x >= 1; x--){ display_for += x + "<BR>"; } document.getElementById("fordemo").innerHTML = display_for;
An example to increase by more than one
In 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 using in the parenthesis:
See online demo and code
You can see, the value of the variable is incremented by ten in each iteration. This code is used:
for (x=10; x <= 100; ){ display_for += x + "<BR>"; x = x + 10; } document.getElementById("fordemo").innerHTML = display_for;
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 to iterate through the array elements quite easily. In the following examples, I will show you how to display array elements that are numeric 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. See the code and output online:
See online demo and code
In the for loop, the initialization and increment operator are the same as used in the first example. However, to specify the condition, the length property of arrays is used. The length property returns the total number of elements in an array.
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 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:
document.getElementById(“div_demo”).innerHTML = displayArray;
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.
See online demo and code
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>
An example of using variables as range in for loop
In 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;
You may use a variable there as well to run the for loop if you are not sure how many times a for loop should execute. For example, a selection from the user in a web form.
In this example, as 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 elements created on the fly.
First have a look at the demo and then I will explain how for loop is used in that example:
See online demo and code
At the onChange event of HTML select dropdown, a JS function is called. Inside the function, the selected number is used in the for loop to creating 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; }