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:
Javascript
<script>
const student = {
registration: '12342' ,
name: 'Sandeep' ,
age: 27,
marks: 98
};
for (const key in student) {
console.log(key);
}
</script>
|
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.
HTML
< 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 >
|
Output:
true
true
true
false
Note: Properties that are created using the defineProperty() method have the 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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
19 Dec, 2022
Like Article
Save Article