An enumerable property is one that can be included in and visited during for/in loops (or a similar iteration of properties, like Object.keys()).

// Enumerable
var man = {age: 18, name: 'Shane'};

for(var key in man) {
  // age
  // name
  console.log(key);
}

So in this example shows age and name as they are are both enumerable properties. This is because their enumerable attribute is set to true.

You can also check if an object has a property using hasOwnProperty(prop). However this won’t show non-enumerable properties.

// true
man.hasOwnProperty('age')
// false
man.hasOwnProperty('hair')
// false
man.hasOwnProperty('toString')

You can use getOwnPropertyDescriptor to check whether or not an enumerable property is true or false.

var descriptor = Object.getOwnPropertyDescriptor(man, 'age');

// Object { value: 18, writable: true, enumerable: true, configurable: true }
console.log(descriptor);

Objects have many more properties (toString, valueOf, hasOwnProperty) but these are hidden from loops because they are non-enumerable.

// Array [ "toSource", "toString", "toLocaleString", "valueOf", "watch", "unwatch", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "__defineGetter__", 5 more… ]
console.log(Object.getOwnPropertyNames(Object.prototype));

// true
console.log('toString' in man);

Stack OverflowJonathan Lonowski

You can also make your own non-enumerable properties using Object.defineProperty.

Object.defineProperty(man, 'sex', { value: 'male', enumerable: false });

for(var key in man) {
  // Sex not visible in loop
  // age
  // name
  console.log(key);
}

var newProp = Object.getOwnPropertyDescriptor(man, 'sex');

// False
console.log(newProp.enumerable);

This then begs the question what is the purpose of hiding these properties in loops? I understand it’s so that it can be accessed at any time, but there is no need for it to be included in an iteration.

Nice example from carpeliam on Stack Overflow.

“So normally, when people want to add a method to Object, such as a polyfill for some method not supported in old browsers, they modify the prototype. But that makes the property enumerable and messes up what is returned in loops/keys collection (without using .hasOwnProperty…which not everyone uses).”

Worthy of Note

Worthy of Note is a site aimed at Web Designers & Developers. It offers a wide range of resources to help assist anyone in the web industry.

View