DEV Community

pampapati
pampapati

Posted on

JavaScript for...in iteration

In this post will try to showcase different ways for the iterations.

  • using forEach
  • using for...of
  • using for...in
  • using for
let list = [1,2];
list.newCustomElement = true;

list.forEach( (item)=>{
console.log(item);
});

//Output 
1
2


for(let item of list){
console.log("using of",item);
}

//Output 
"using of", 1
"using of", 2

for(let item in list){
console.log("using in",item);
}

//Output 
"using in", "0"
"using in", "1"
"using in", "newCustomElement"



for(let i=0;i<list.length;i++){
console.log(list[i]);
}
//Output 
1
2

Enter fullscreen mode Exit fullscreen mode

Don't use for...in to iterate the array , if the order is important

Will see another example for better understanding of for..in


const Employee= {
    name: 'John',
    dept: 'IT',
    age: 29
}


for ( let key in Employee) {
    console.log(key);
}

Output:
"name"
"dept"
"age"

for ( let key in Employee) {
    console.log('key: ',key,' value:', Employee[key]);
}

Output:
"key: ", "name", " value:", "John"
"key: ", "dept", " value:", "IT"
"key: ", "age", " value:", 29
Enter fullscreen mode Exit fullscreen mode

In above example for...in is used to print properties on Employee object.

First for loop in above example will showcase that object keys are printed using iterator key, it wont print the values of property.

Second for loop in above example will showcase how to print keys and the values of property.

Top comments (0)