for-in is 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 a key on each iteration.
It works with both –
- Array and
- Object
Contents
1. Loop on Array With for-in
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. Loop on Object With for-in
The syntax is similar to 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.
The same operation you can also do with the $.each() method in jQuery which also works with selectors.
If you found this tutorial helpful then don't forget to share.