JavaScript Enumerability
May 27, 2021
JavaScript object properties have an enumerable
property that controls whether that property shows up in for/in
loops and the Object.keys()
function.
If you create a POJO using {}
, all the POJO's properties will be enumerable by default.
const obj = {
name: 'Jean-Luc Picard',
age: 59
};
Object.keys(obj); // ['name', 'age']
However, you can also define a property on an object using the Object.defineProperty()
function.
Set enumerable
to false
and that property won't show up in Object.keys()
.
Object.defineProperty(obj, 'hidden', {
enumerable: false,
value: 42
});
obj.hidden; // 42
Object.keys(obj); // ['name', 'age'], no 'hidden'!
You can check if a property
if enumerable using the propertyIsEnumerable()
function which returns
a Boolean.
const obj = { name: 'first' };
obj.propertyIsEnumerable('name'); // true
More Fundamentals Tutorials
- How to Add 2 Arrays Together in JavaScript
- The String `match()` Function in JavaScript
- Convert a Set to an Array in JavaScript
- What Does Setting the Length of a JavaScript Array Do?
- Get the Last Element in an Array in JavaScript
- Skip an Index in JavaScript Array map()
- Conditionally Add an Object to an Array in JavaScript