Friday, December 27, 2024
Google search engine
HomeLanguagesJavascriptWhat does enumerable property mean in JavaScript?

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: 

Javascript




<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>


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

RELATED ARTICLES

Most Popular

Recent Comments