What Are "Enumerable Properties" in a JavaScript Object?

Find out what is meant by enumerable keys of a JavaScript object

An object can have enumerable properties, as well as non-enumerable properties. The difference is that the former allows the property to be available when looping while the latter doesn't.

For example, you can specify a property to be non-enumerable with Object.create() like so:

const obj = Object.create({}, {
    foo: {
        value: 123,
        enumerable: false,
    },
    bar: {
        value: 'baz',
        enumerable: true,
    },
});

for (const key in obj) {
    console.log(key, obj[key]);
}

// output: 'bar' 'baz'

Similarly, for an existing object, you can define a property (new or old) to be non-enumerable using Object.defineProperty(), in the following way:

const obj = {};

Object.defineProperty(obj, 'foo', {
    value: 123,
    enumerable: false,
});

console.log(obj); // { foo: 123 }
console.log(Object.keys(obj)); // []

In the examples above, you can see that the Object.keys() method returns an empty array. This happens because the Object.keys() method only returns object's own enumerable properties.

To define multiple properties, you may use Object.defineProperties(), which functions in a similar way:

const obj = {};

Object.defineProperties(obj, {
    foo: {
        value: 123,
        enumerable: false,
    },
    bar: {
        value: 'baz',
        enumerable: true,
    },
});

console.log(obj); // { foo: 123 }
console.log(Object.keys(obj)); // ['bar']

Hope you found this post useful. It was published . Please show your love and support by sharing this post.