How to make a property non-enumerable in JavaScript?

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,

  1. Object
  2. Property name as string
  3. Property descriptor

There are three property descriptors such as,

  1. Writable
  2. Enumerable
  3. Configurable

However, to make a property non-enumerable, you set the enumerable property to false.  I hope you find this useful. Thanks for reading.


Discover more from Dhananjay Kumar

Subscribe to get the latest posts sent to your email.

Published by Dhananjay Kumar

Dhananjay Kumar is founder of NomadCoder and ng-India

Leave a comment

Discover more from Dhananjay Kumar

Subscribe now to keep reading and get access to the full archive.

Continue reading