What does this Moz explanation means (Object.entries)?

This is about the difference between Object.entries and a for in loop: entries does the same as the loop, except for this: " The only important difference is that a for...in loop enumerates properties in the prototype chain as well". Could you please put this into simple words?

please do not post in #support for help with coding. You have no issues with the freecodecamp platform or the forum so this is the wrong place to post.

have you already completed the Object Oriented Programming section?
there it introduces objects, and the prototype chain

Yes , I did.
Prototype chain is the way objects inherit methods. For example, Array prototype methods are available for arrays because of the prototype chain… ¿or not?

Hello!

It means that by using Object.entries you will not get the properties defined on the prototype, only the ones defined on the initial object:

function Animal(name) {
    this.name = name;
}

Animal.prototype.isAnimal = true;

function Dog(name) {
    Animal.call(this, name);
    this.bark = () => "Woof!";
    this.moveTail = () => "Moves tail!";
}

Dog.prototype = Object.create(Animal.prototype);
Object.defineProperty(Dog.prototype, "constructor", {
    value: Dog,
    enumerable: false,
    writable: true
})

const jason = new Dog("Jason");

for (let p in jason) {
    console.log('Property:', p);
}

console.log('Object.entries:', Object.entries(jason));
// Output:
// Property: name
// Property: bark
// Property: moveTail
// Property: isAnimal
//
// Object.entries:
// [
//     [ "name", "Jason" ],
//     [ "bark", null ],
//     [ "moveTail", null ]
// ]

Look at this sample.

Hope it helps.

2 Likes

Hi. Thanks! Now I feel more acquainted with. The OOP section doesn’t shed enough light on this (the subject is NOT obvious at all). I’m gonna study the Object methods and maybe come back here.
As far as I see right now, for in throws the prototype context (the whole chain) of a current instance, while Object entres just return the first layer, where the current object is in.

I found this quite useful:

for in prints all the iterables (enumerable properties ¿right?) including those inherited through the prototype chain, whereas for of just prints the array elements (which are not enumerable but values)

Object.prototype.enumFun = function(){};
Array.prototype.littleEnumFun = function (){};


const iterable = [1, 2, 3];
iterable.forth = 4;

for (let i in iterable){
  console.log(i)//--> 0 1 2 forth littleEnumFun enumFun
}
for (let j of iterable){
  console.log(j)//--> 1 2 3
}

Notice how the two first code lines make possible that iterable inherits from Array (because is an array) but also from Object (because arrays are --special-- objects)
Sources: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

and see this: