How can I loop through an array of objects in JavaScript and access their properties?

I’m trying to iterate through an array of objects and modify their properties. When I try this:

for (var j = 0; j < myArray.length; j++) {
  console.log(myArray[j]);
}

It only logs the first object, even though the array contains more. Also, when I try to access properties like Object1.x within the loop:

for (var j = 0; j < myArray.length; j++) {
  console.log(myArray[j.x]);
}

It returns undefined. The properties are definitely present outside the loop. How can I correctly access these properties while looping through the array of objects in JavaScript?

*’ve been working with JavaScript for quite a few years, and honestly, the classic for loop still holds up in many use cases.

When you’re trying to javascript loop through array of objects, the most fundamental method is the traditional for loop. It gives you full control, especially when you need the index:

for (var j = 0; j < myArray.length; j++) {
  console.log(myArray[j].x); // Access the 'x' property of each object
}

This works well when you need to manipulate the array by index or perform more complex logic. Just make sure you’re accessing properties correctly, myArray[j].x, not myArray[j.x]. The latter will throw you off because it’s not syntactically valid.

“I’ve found that as your codebase grows, readability matters more. That’s where modern methods come into play.”

So, building on what @joe-elmoufak said, if you’re still looking to javascript loop through array of objects but want something cleaner and easier to read, I’d go with forEach:

myArray.forEach(function(obj) {
  console.log(obj.x); // Access the 'x' property of each object
});

It automatically gives you access to each object without needing the index. This makes your code cleaner and less error-prone. Plus, it’s perfect for side-effect operations like logging, updating values, or calling functions.

After working on several ES6+ projects, I lean heavily on more modern, expressive loops.

Both the classic for loop and forEach are solid, but when I need a more elegant and modern syntax to javascript loop through array of objects, I go with the for...of loop:

for (let obj of myArray) {
  console.log(obj.x); // Access the 'x' property of each object
}

It’s concise, readable, and doesn’t expose the index unless you need it. I especially prefer it when working with large data sets where clarity is key. It just feels more natural when looping through objects in an array.