JavaScript for...in loop Explained

I am a JavaScript Developer/Technical Writer/Researcher..
The for...in loop is the conventional way of listing the properties of an object in JavaScript. This article will guide you in understanding for...in loop.
The syntax of the for...in loop is:
for(let variableName in object){
//execute code
}
From the above syntax, each property of the object is assigned a variableName that will be used within the block scope.
Let's take a better example:
const profile = {
name: "Ciroma Adekunle",
age: 18
}
for (let prop in profile){
console.log(`${prop}: ${profile[prop]}`)
}
The profile object is iterated and each property is assigned to prop. With that we are able to log to the console not just the properties (keys) but also their values.
Output:
name: Ciroma Adekunle
age: 18
In Array
Although possible, it is not advisable to use a for...in loop in an array for iteration. A simple for loop or forEach is recommended instead for arrays.
For instance:
let items = [5, 10, 15, 20];
// add a value to the sixth element
items[5] = 30
for(let i = 0; i < items.length; i++) {
console.log(`${i}: ${items[i]}`)
}
The output will be:
0: 5
1: 10
2: 15
3: 20
4: undefined
5: 30
When we use the for...in loop:
let items = [5, 10, 15, 20];
// add a value to the sixth element
items[5] = 30
for(const item in items) {
console.log(`${item}: ${items[item]}`)
}
The output will be:
0: 5
1: 10
2: 15
3: 20
5: 30
You will notice that for...in loop ignores the undefined element. This affects the order of the array elements.
In Object inheritance
When you iterate the properties of an object that inherits from another object, the inherited properties are listed. For example:
const furniture = {
chair: 'one'
};
const house = Object.create(furniture);
house.room = 3;
for(const prop in house) {
console.log(prop);
}
The output:
room
chair
We can also list just the property of the house object using the hasOwnProperty() object method
for(const prop in house) {
if(house.hasOwnProperty(prop)) {
console.log(prop);
}
}
The output:
room
Summary
The
for...inloop is used to list the properties of an object.Using
for...inloop to iterate an array is not advisable, as it affects the order of the elements.for...inloop also returns the properties of any inherited object. ThehasOwnProperty()method lists only the properties of an object.




