for-in loop in JavaScript

for-in is an another type of looping statement within JavaScript. Which works similarly like a foreach loop in PHP.

When performing iteration with for-in then it returns key on each iteration.

It works with both –

  1. Array and
  2. Object

for-in loop in JavaScript


Contents

  1. With Array
  2. With Object
  3. Conclusion

1. With Array

First start with performing iteration over an Array.

Syntax –
for(key in Array){
 // statement
}

Single Dimensional Array

var names_arr = ["Yogesh","Sonarika","Vishal","Anil"];
for(var key in names_arr){
 console.log("index :  " + key + ", name :  " + names_arr[key]);
}
Here, I created a names_arr Array when looping over this Array then it returns key from it and using this key to take out the value from the names_arr Array.
Output
index : 0 , name : Yogesh
index : 1 , name : Sonarika
index : 2 , name : Vishal
index : 3 , name : Anil

Multi-Dimensional Array

var names_arr = [ ["Yogesh",23],["Vishal",24],["Sonarika",23],["Anil",22] ];
for(var key in names_arr){
 console.log( "index : " + key + " , name : " + names_arr[key][0] + ", age : " + names_arr[key][1] );
}

Output

index : 0 , name : Yogesh , age : 23
index : 1 , name : Vishal , age : 24
index : 2 , name : Sonarika , age : 23
index : 3 , name : Anil , age : 22

2. With Object

The syntax is similar like an Array.

Syntax –

for(key in Object){
 // statement
}
Example
var obj = {'yogesh': 23,'Sonarika': 23, 'Vishal': 24};
for(var key in obj){
 if(obj.hasOwnProperty(key)){
  console.log('name : ' + key + ', age : ' + obj[key]);
 }
}
Here,  In the example, I iterate over an Object  which has the name as key and age as a value.
Output
name : yogesh , age : 23
name : Sonarika , age : 23
name : Vishal , age : 24

3. Conclusion

for-in is a good choice when you want to traverse over an Object and Array. This will return key while iteration.

The same operation you can also do with the $.each() method in jQuery which also works with selectors.

Spread the love

Related Post

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *