In this episode, we dive into different ways to iterate over JavaScript objects. At first, we create a simple user
object with properties like name
and age
, and explore the classic for...in
loop to go through those properties. We also discuss some caveats with for...in
, especially how it can pick up properties from the prototype chain—which can lead to accidentally grabbing methods or properties you don't want!
To avoid this problem, we show how to use hasOwnProperty
inside the loop so you only get the object's own properties, not inherited ones. But since there's a cleaner and more modern way to do this, we introduce Object.entries()
. This method gives us an array of key-value pairs from our object, letting us use a nice for...of
loop or even the convenient forEach
method with destructuring to access both the key and value in a tidy, readable way.
By the end, you'll see why Object.entries()
is the preferred way for most use cases, making your code shorter and easier to understand. If you've ever fumbled with object iteration in JavaScript, this episode shows you the "clean" way to do it!