What is the importance of "enumerable" attribute in defining a property in JavaScript object?

The enumerable attribute controls whether a property appears in object enumeration methods like for...in loops, Object.keys(), and JSON.stringify(). When using Object.defineProperty(), properties are non-enumerable by default.

Syntax

Object.defineProperty(objectName, propertyName, {
    value: propertyValue,
    enumerable: true/false
})

Default Behavior: Non-enumerable Property

When enumerable is not specified, it defaults to false, making the property invisible to enumeration methods:

<html>
<body>
<script>
    var object = {one: 1};
    Object.defineProperty(
        object,
        'two', {
            value: 2
        }
    );
    document.write("JSON.stringify: " + JSON.stringify(object) + "<br>");
    document.write("Object.keys: " + Object.keys(object));
</script>
</body>
</html>

Output

JSON.stringify: {"one":1}
Object.keys: one

Setting enumerable: true

To make the property visible in enumeration, set enumerable: true:

<html>
<body>
<script>
    var object = {one: 1};
    Object.defineProperty(
        object,
        'two', {
            value: 2,
            enumerable: true
        }
    );
    document.write("JSON.stringify: " + JSON.stringify(object) + "<br>");
    document.write("Object.keys: " + Object.keys(object));
</script>
</body>
</html>

Output

JSON.stringify: {"one":1,"two":2}
Object.keys: one,two

Comparison with Regular Property Assignment

Properties created with dot notation or bracket notation are enumerable by default:

<html>
<body>
<script>
    var object = {};
    object.regularProp = "visible";
    Object.defineProperty(object, 'hiddenProp', {
        value: "hidden",
        enumerable: false
    });
    
    document.write("All properties exist: " + (object.regularProp && object.hiddenProp) + "<br>");
    document.write("Only enumerable in JSON: " + JSON.stringify(object));
</script>
</body>
</html>

Output

All properties exist: true
Only enumerable in JSON: {"regularProp":"visible"}

Common Use Cases

Non-enumerable properties are useful for:

  • Internal methods that shouldn't appear in object serialization
  • Metadata properties that shouldn't be copied during object cloning
  • Configuration properties that should remain hidden from enumeration

Conclusion

The enumerable attribute determines property visibility in enumeration operations. Use enumerable: false for internal properties and enumerable: true to make properties visible in loops and serialization.

Updated on: 2026-03-15T23:18:59+05:30

399 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements