JavaScript - For In Loop
JavaScript For In Loop
The for...in statement is used to loop through the properties of an object. The syntax for using for in loop is given below:
Syntax
for(key in object){ statements; }
On each iteration, one property from object is assigned to variable key and executes the given code statements. The loop continues doing the same till all properties of the object are exhausted.
For In Loop over an Array
In the example below, the for in loop is used to iterate over an array. It is used to print array elements.
var Arr = [10, 20, 30, 40, 50]; var txt = ""; for (i in Arr) txt = txt + Arr[i] + "<br>";
The output (value of txt) after running above script will be:
10 20 30 40 50
Note: Please note that the index order of an array is implementation-dependent. Accessing elements of an array using for in loop may give you the different result. It is better to use for loop, for of loop or Array.forEach() function instead.
Array.forEach() function
Array.forEach() function returns value of elements of the array one by one. In the example below, a function is created which takes a value and print it.
var Arr = [10, 20, 30, 40, 50]; var txt = ""; Arr.forEach(MyFunction); function MyFunction(value) { txt = txt + value + "<br>"; }
The output (value of txt) after running above script will be:
10 20 30 40 50