For-in loop is used to iterate through an object. Let is suppose you have an object as following

 

image

You can iterate through object properties using for-in loop. You can iterate as following listing,

 

image

You will get output as following,

image

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

 

image

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

 

image  

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.

 

image

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,

 

image

You will get array element traversed as following. You see that now unassigned array elements has been skipped.

image

So you see that in this way you can use for-in loop in JavaScript. I hope you find this post useful. Thanks for reading.


Advertisements

3 thoughts on “For-in loop in JavaScript Array

  1. No no no no no! Don’t do this! The for loop iteraties the properties on a object, NOT items in a collection. For plain jane arrays it might work as in this case the properties and items happen to be the same thing, but other times the behaviour may be unexpected.

  2. You can do this with a short-circuit statement (prevents a new call-stack) in an iterator with an array of objects too. Not the same as for-in, but useful for skipping undefined elements in arrays of objects. example:

    [ {id: 1, name: ‘banana’, price: 1.20},
    undefined,
    {id: 3, name: ‘apple’, price: .89},
    undefined,
    {id: 5, name: ‘orange’, price: 1.30}
    ].forEach(function(product) {
    // console.log() is not called if product is undefined
    product && console.log(‘id:’, product.id, ‘\tname:’, product.name, ‘\tprice:’, product.price)
    })

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s