The Object.propertyIsEnumerable()
method checks if the given property is enumerable and is the object's own property.
Example
let arr = [1, 2, 3, 4];
// check whether the element at
// index 0 is enumerable or not
console.log(arr.propertyIsEnumerable(0));
// Output: true
// check whether length is enumerable or not
console.log(arr.propertyIsEnumerable(arr.length));
// Output: false
propertyIsEnumerable() Syntax
The syntax of the propertyIsEnumerable()
method is:
obj.propertyIsEnumerable(prop)
Here, obj is the object whose property (prop) needs to be checked for enumerability.
propertyIsEnumerable() Parameters
The propertyIsEnumerable()
method takes in:
- prop - the name of the property to test
propertyIsEnumerable() Return Value
The propertyIsEnumerable()
method returns:
true
- if the property is enumerable and exists in the objectfalse
- if the property is either not enumerable or if it doesn't exist in the object
Note: Every object has a propertyIsEnumerable()
method. This method can determine whether the specified property in an object can be enumerated by a for...in loop.
Example 1: JavaScript Object.propertyIsEnumerable()
// create a simple object
let obj = {
message: "Hello World!",
};
// check if prop is enumerable
console.log(obj.propertyIsEnumerable("message"));
// Output: true
// check a property that does not exist in the object
console.log(obj.propertyIsEnumerable("random"));
// Output: false
In the above example, the propertyIsEnumerable()
method returns true
as an output as a message exists in the object obj and is enumerable.
However, we get false
as an output while checking whether the non-existent property random is enumerable or not.
Example 2: propertyIsEnumerable() With Built-in Objects
console.log(Math.propertyIsEnumerable("random"));
// Output: false
console.log(Math.propertyIsEnumerable("E"));
// Output: false
In the above example, the propertyIsEnumerable()
method returns false
as output while checking whether random and E are enumerable or not.
Here, random and E are two properties of the built-in Math object in JavaScript.
Note: User-created properties are often enumerable (unless explicitly set to false
), while most built-in properties are non-enumerable by default.
Also Read: