JavaScript ES6 For in loop with example

JavaScript

In this post, we are going to understand JavaScript ES6 For in loop with code example, how and where to use it.

What is For in loop in JS ES6?


The for-in loop iterate through the property of an object. The code inside the for-in loop body executes for each property of the object. For in loop iterate enumerable and non-symbol properties of an object.

  • Note: For ….in a loop is not recommended to be used with the array.
  • Use: It is mostly used to check the property of an object.If we need to check some property hold a specific value.

Syntax of For in loop

In for in loop on each iteration, one property of given object is assigned to variable and this loop execute continues until all the properties of the object are exhausted.

for (variable in object)
{
//code here
}

For in JavaScript ES6 Examples


1. Iterate over array of objects

In this example, we are iterating over an array of objects using the JS ES6 for-in loop.

In this example property of object Students is assign to stu variable and this loop continue run till the all property of students object is exhausted.

let Students = [{
     id:1,
     name:"Jack",
	 Section:'B'
   },
   {
     id:2,
     name:"Ram",
	 Section:'A'
	 
   },
  {
    id:3,
    name:"Sika",
	Section:'A'
  }]
for(let stu in Students){
   console.log(`${Students[stu].id} ${Students[stu].name}  ${Students[stu].Section}`);
}

Output:

1 Jack  B
2 Ram  A
3 Sika  A

2. For in loop access object property without name

By using the for-in loop we can access each property of an object without a property name.

We can access property using this synatx:

object[property]

In this example we are accessing property of object Students

let Students = {
     id:1,
     name:"Jack",
   	Section:'A'
   	
  };
for(var prop in Students) {
    console.log(prop + ':' + Students[prop]);
}

Output

id:1
name:Jack
Section:A

Summary:

In this post,We have learned JavaScript ES6 For in loop with example, The for-in loop iterate through the property of an object. The code inside the for-in loop body executes for each property of the object. For in loop iterate enumerable and non-symbol properties of an object