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:
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 theenumerable
attribute set tofalse
will not be counted as enumerable.
Example 1: Basic Usage
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
Here, prop
is defined as a non-enumerable property, so propertyIsEnumerable
returns false
.
Example 3: Using with Symbols
In this case, the symbol property is created directly on the object, and since it is enumerable, propertyIsEnumerable
returns true
.
Example 4: Prototype Properties
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.