JavaScript Obj.propertyIsEnumerable(prop) method


The obj.propertyIsEnumerable(prop) method in JavaScript is used to determine whether a specified property is an enumerable property of an object. It returns a boolean value indicating whether the property can be enumerated in a for...in loop or in methods like Object.keys().

Syntax:

obj.propertyIsEnumerable(prop);

Parameters:

  • prop: A string (or symbol) representing the name of the property to check.

Return Value:

  • true: If the property exists on the object and is enumerable.
  • false: If the property does not exist on the object, or if it is non-enumerable.

Key Features:

  • Enumerable vs. Non-Enumerable Properties: Properties defined directly on an object can be marked as enumerable or non-enumerable. Enumerable properties are those that will show up in loops and methods that list properties.
  • Non-Enumerable Properties: By default, properties created with Object.defineProperty() with the enumerable attribute set to false will not be counted as enumerable.

Example 1: Basic Usage

const obj = { name: 'Alice', age: 30 }; console.log(obj.propertyIsEnumerable('name')); // Output: true console.log(obj.propertyIsEnumerable('age')); // Output: true console.log(obj.propertyIsEnumerable('gender')); // Output: false

In this example, name and age are enumerable properties, while gender does not exist on the object, so it returns false.

Example 2: Checking Non-Enumerable Properties

const obj = Object.create({}, { prop: { value: 42, enumerable: false } }); console.log(obj.propertyIsEnumerable('prop')); // Output: false

Here, prop is defined as a non-enumerable property, so propertyIsEnumerable returns false.

Example 3: Using with Symbols

const sym = Symbol('unique'); const obj = { [sym]: 'symbol value' }; console.log(obj.propertyIsEnumerable(sym)); // Output: true

In this case, the symbol property is created directly on the object, and since it is enumerable, propertyIsEnumerable returns true.

Example 4: Prototype Properties

const parent = { inheritedProp: 'I am inherited' }; const child = Object.create(parent); console.log(child.propertyIsEnumerable('inheritedProp')); // Output: false

In this example, inheritedProp is not an own property of child but inherited from parent, so the method returns false.

Summary:

  • obj.propertyIsEnumerable(prop) is a method that checks whether a specified property is an enumerable property of the object.
  • It can be useful for differentiating between properties that can be enumerated and those that cannot, such as non-enumerable properties created via Object.defineProperty().
  • This method aids developers in understanding how properties are structured within objects, especially when dealing with property enumeration in loops or functions that rely on property listing.