What language constructs do you use for iterating over object properties and array items in JavaScript?
By FrontendPro Editorial Team Updated 8/8/2026
Answer
There are multiple ways to iterate over object properties as well as arrays in JavaScript:
for...in loop
The for...in loop iterates over all enumerable properties of an object, including inherited enumerable properties. So it is important to have a check if you only want to iterate over the object's own properties.
const obj = {
a: 1,
b: 2,
c: 3,
};
for (const key in obj) {
// To avoid iterating over inherited properties
if (Object.hasOwn(obj, key)) {
console.log(`${key}: ${obj[key]}`);
}
}
Object.keys()
Object.keys() returns an array of the object's own enumerable property names. You can then use a for...of loop or forEach to iterate over this array.
const obj = {
a: 1,
b: 2,
c: 3,
};
Object.keys(obj).forEach((key) => {
console.log(`${key}: ${obj[key]}`);
});
The most common ways to iterate over an array are using a for loop and the Array.prototype.forEach method.
Using for loop
let array = [1, 2, 3, 4, 5, 6];
for (let index = 0; index < array.length; index++) {
console.log(array[index]);
}
Using Array.prototype.forEach method
let array = [1, 2, 3, 4, 5, 6];
array.forEach((number, index) => {
console.log(`${number} at index ${index}`);
});
Using for...of
This method is the newest and most convenient way to iterate over arrays. It automatically iterates over each element without requiring you to manage the index.
const numbers = [1, 2, 3, 4, 5];
for (const number of numbers) {
console.log(number);
}
There are also other built-in methods available which are suitable for specific scenarios, for example:
Array.prototype.filter: You can use thefiltermethod to create a new array containing only the elements that satisfy a certain condition.Array.prototype.map: You can use themapmethod to create a new array based on the existing one, transforming each element with a provided function.Array.prototype.reduce: You can use thereducemethod to combine all elements into a single value by repeatedly calling a function that takes two arguments: the accumulated value and the current element.
Read the detailed answer on GreatFrontEnd which allows progress tracking, contains more code samples, and useful resources.
