For-in loop is used to iterate through an object. Let is suppose you have an object as following
You can iterate through object properties using for-in loop. You can iterate as following listing,
You will get output as following,
In other way you can for-in loop with an array. However that is not advisable. Since sometime for-in loop does not iterate an array in correct sequence of index. But let us go brave here and see, how we could use for-in loop with an array.
Let us assume that there is an array as given in below listing
You can see that size of the array is 6 and 4t and 5th element of the array is not assigned. Using for loop you can traverse the array as following
In loop we are traversing each element one by one and printing the value of element. You see that value of 4th element and 5th element also got printed with value undefined. And it was expected since we did not assign value at these indexes of array.
Now if you traverse the same array using for-in, you will get only value of the assigned element in the array. For-in skips the unassigned elements while traversing. If you traverse above array as using for-in as following,
You will get array element traversed as following. You see that now unassigned array elements has been skipped.