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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com