What is non-enumerable property in JavaScript and how can it be created?


Non-enumerable property

Objects can have properties that don't show up when iterated through the particular object using Object.keys() or for...in loop.Those type of properties are called as non-enumerable properties.

Creating a non-enumerable property

To create a non-enumerable property we have to use Object.defineProperty() method. This a special method to create non-enumerable properties in an object. 

In the following example, three properties such as name, age and country were created normally and a property named "salary" was created using Object.defineProperty() method and key named enumerable was assigned with false. When the object "person" got iterated using Object.keys() the properties such as name, age and country were shown up whereas property "salary" was unable to shown up. Since salary property was unable to shown up it is called as non-enumerable property. This is the way to create non-enumerable properties.

Object.defineProperty() is also let you create read-only properties as we saw below, we are not able to modify salary value of a person object. To make the salary property enumerable assign true to the key named enumerable.

Example

Live Demo

<html>
<body>
<script>
   var person = {
      name: 'gopal'
   };
   person.age = '21';
   person['country'] = 'India';
   Object.defineProperty(person, 'salary',{
      value : '80,000$',
      enumerable: false
   })
   document.write(Object.keys(person));
</script>
</body>
</html>

Output
name,age,country

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements