Sobes.tech
Junior

What does 'enumerable' mean in JavaScript?

sobes.tech AI

Answer from AI

enumerable is an attribute of an object property descriptor in JavaScript. It determines whether the property will be listed during for...in loops or methods like Object.keys(), Object.values(), and Object.entries().

By default, most properties created with assignment operators or object literals are enumerable (enumerable: true). Properties added with Object.defineProperty() or Object.defineProperties() are not enumerable by default (enumerable: false), unless explicitly specified otherwise.

Non-enumerable properties are not included in the results of these operations but remain accessible directly (e.g., object.property) and can be retrieved using Object.getOwnPropertyNames() or Object.getOwnPropertySymbols().

Example:

const obj = {
  a: 1, // Enumerable by default
};

Object.defineProperty(obj, 'b', {
  value: 2,
  enumerable: false // Not enumerable
});

Object.defineProperty(obj, 'c', {
  value: 3,
  enumerable: true // Explicitly enumerable
});

console.log(Object.keys(obj));
// Output: ['a', 'c'] - 'b' is not included

for (const key in obj) {
  console.log(key);
}
// Output:
// a
// c
// 'b' is not enumerated in the for...in loop

console.log(obj.b);
// Output: 2 - accessible directly
What does 'enumerable' mean in JavaScript? — Node.js - sobes.tech