DEV Community

Cover image for Do You Really Know What's Inside Your Object? Or Are You Just Trusting for...in?
Werliton Silva
Werliton Silva

Posted on

Do You Really Know What's Inside Your Object? Or Are You Just Trusting for...in?

“for...in is that teammate who talks to everyone, even the receptionist's coffee machine. Object.entries(), on the other hand, only responds if tagged on Slack.”


🔍 The Issue at Hand

I was reviewing someone else's code and came across this snippet:

// Student inheriting the 'name' attribute from person
const person = { name: 'Werliton Silva' };
const student = Object.create(person);

student.id = 12;
student.age = 25;
Enter fullscreen mode Exit fullscreen mode

Later on, there was a need to list all properties of the object using a loop:

for (let [key, value] of Object.entries(student)) {
    console.log(key, value);
}
// Console output:
// id 12
// age 25
Enter fullscreen mode Exit fullscreen mode

The developer used Object.entries(student) expecting the name property to appear.

And I thought:

"Buddy, you've fallen into the classic JavaScript trap."


🤔 Why Doesn't 'name' Show Up?

Because Object.entries() (just like Object.keys() and Object.values()) only returns the object's own properties.

If the value comes from the prototype (i.e., inherited), it's gracefully ignored.

It's like that distant relative you only remember at Christmas. They're part of the family but not invited to Sunday barbecues.


✅ Who Brings Everything, Even What You Didn't Ask For?

The good old for...in.

for (let key in student) {
    console.log(key, student[key]);
}
// Console output:
// id 12
// age 25
// name Werliton Silva
Enter fullscreen mode Exit fullscreen mode

This loop is the gossip. It fetches id, age, and the inherited name from the prototype chain.

It's useful—but be cautious not to bring in too much into your loop.


🕵️‍♂️ Want to Know Where Each Property Comes From?

Use the legendary hasOwnProperty():

for (let key in student) {
    const origin = student.hasOwnProperty(key) ? 'own' : 'inherited';
    console.log(`${key}: ${student[key]} (${origin})`);
}
// Console output:
// id: 12 (own)
// age: 25 (own)
// name: Werliton Silva (inherited)
Enter fullscreen mode Exit fullscreen mode

Now you're the Sherlock Holmes of prototyping. You can even create a neat console.table() and log it in production. (Just kidding. Or not.)


🧠 Conclusion

If you're using Object.entries() thinking it will list everything, it's like me thinking I can cook just because I make instant noodles with an egg.

Know your tools.

More importantly: understand how inheritance works in JavaScript.

It's beautiful, powerful, and as treacherous as a bug on a Friday at 5 PM.


Werliton Silva

Frontend Specialist | Bug Hunter | Evangelist of hasOwnProperty() since 2012

Top comments (2)

Collapse
 
michael_liang_0208 profile image
Michael Liang

Nice post!

Collapse
 
werliton profile image
Werliton Silva

Thanks, bro!