
By default, all the properties of JavaScript objects are enumerable. That means you can enumerate them in a for loop or read them using the Object.values().
Let us consider an object Dog as shown below,
let Dog = {
name :'foo',
age: 9,
canRun : true,
eatMilk : false
}
You can enumerate all properties and read their values using the for loop or Object.values() method as shown below,
for(let p in Dog){
console.log(Dog[p]);
}
console.log(JSON.stringify(Dog));
console.log(Object.values(Dog));
Now let us say you don’t want to enumerate eatMilk property. You can achieve that using a property descriptor Object.defineProperty() as shown below,
Object.defineProperty(Dog,'eatMilk',{enumerable:false});
// eatMilk property is not enumerable
for(let p in Dog){
console.log(Dog[p]);
}
console.log(JSON.stringify(Dog));
console.log(Object.values(Dog));
The Object.defineProperty takes three parameters,
- Object
- Property name as string
- Property descriptor
There are three property descriptors such as,
- Writable
- Enumerable
- Configurable
However, to make a property non-enumerable, you set the enumerable property to false. I hope you find this useful. Thanks for reading.
Leave a Reply