DEV Community

Randy Rivera
Randy Rivera

Posted on

Iterating Over All Properties

  • You have now seen two kinds of properties: own properties and prototype properties. Own properties are defined directly on the object instance itself. And prototype properties are defined on the prototype.
function Dog(name) {
  this.name = name; // own property
}

Dog.prototype.numLegs = 4; // prototype property

let beagle = new Dog("Snoopy"); 
Enter fullscreen mode Exit fullscreen mode
  • Here is how you add dog's own properties to the array ownProps and prototype properties to the array prototypeProps:
let ownProps = [];
let prototypeProps = [];

for (let properties in beagle) {
  if (beagle.hasOwnProperty(properties)) {
    ownProps.push(properties);
  } else {
    prototypeProps.push(properties);
  }
}

console.log(ownProps); // display ["name"] in the console
console.log(prototypeProps); // display ["numLegs"] in the console
Enter fullscreen mode Exit fullscreen mode

Top comments (0)