What does enumerable property mean in JavaScript?

An enumerable property in JavaScript means that a property can be viewed if it is iterated using the for…in loop or Object.keys() method. All the properties which are created by simple assignment or property initializer are enumerable by default.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
// Creating a student object
const student = {
    registration: '12342',
    name: 'Sandeep',
    age: 27,
    marks: 98
};
  
// prints all the keys in student object
for (const key in student) {
    console.log(key);
}
</script>

chevron_right


Output:

registration
name
age
marks

Example 2: Since all the properties are initialized by property initializer, they all have enumerable set to true by default. To explicitly change the internal enumerable attribute of a property, the Object.defineProperty() method is used. Also, to check whether a property is enumerable or not, we use the function propertyIsEnumerable(). It returns true if the property is enumerable or false otherwise.

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
// Creating a student object
const student = {
    registration: '12342',
    name: 'Sandeep',
    age: 27,
};
  
// This sets the enumerable attribute
// of marks property to false 
  
Object.defineProperty(student, 'marks', {
    value: 98,
    configurable: true,
    writable: false,
    enumerable: false,
});
  
// To print whether enumerable or not
console.log(student.propertyIsEnumerable('registration')); 
console.log(student.propertyIsEnumerable('name'));
console.log(student.propertyIsEnumerable('age'));
console.log(student.propertyIsEnumerable('marks'));
</script>

chevron_right


Output:



true
true
true
false

Note: Properties that are created using the defineProperty() method have enumerable flag set to false. When the same above code is run using a for loop, the “marks” property is not visible.

// This will not print the property 
// Who's enumerable property is set to false

for (const key in student){
    console.log(key)
}

Output:

registration
name
age

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.