All Properties of An Object Enumerable in JavaScript including Number Properties and here is why.
What Is Enumeration ๐คโ
In JavaScript, properties that contain a number value are set to enumerable by default because numbers are a fundamental data type in the language, and it is generally assumed that developers will want to include them when iterating over an object's properties.
Enumeration is the process of iterating over an object's properties and returning a list of property names or values. When an object's properties are enumerable, they can be included in this list, which can be useful for a variety of programming tasks.
By default, all properties that are created using the object literal notation or the Object.create method are enumerable. This includes properties that contain number values, as well as properties that contain other types of data.
However, it's worth noting that there are situations where you may want to make a property non-enumerable, even if it contains a number value. For example, if you have a property that you don't want to be included when iterating over an object's properties, you can set the "enumerable" attribute to "false" when defining the property.
To set a property to non-enumerable in JavaScript, you can use the Object.defineProperty method, like so:
Object.defineProperty(obj, "propertyName", {
value: 42,
enumerable: false,
});
Why Objects Are A Bit Of A Different Case ๐คโ
While talking about an object in Javascript enumerable set on each property of the object implies that the property will be enumerable when iterating through the entire object. We do not talk in context of the value of the property being enumerable or not.
In JavaScript, when we say that a property of an object is enumerable, we mean that the property will be included when iterating over the object's properties using a loop or a method such as Object.keys() or Object.values().
By default, all properties that are added to an object using object literal notation or the Object.create() method are enumerable. This includes properties that contain number values or other data types.
let person = {
name: "John",
age: 30,
getFullName() {
return this.name;
},
};
In this case, all three properties of the person object (name, age, and getFullName()) are enumerable because they were added to the object using object literal notation.
If we wanted to make the getFullName() method non-enumerable, we could use Object.defineProperty() to set the enumerable attribute to false, like so:
Object.defineProperty(person, "getFullName", {
enumerable: false,
});
After this code runs, the getFullName() method will no longer be included when iterating over the person object's properties.
What Can You Do Next ๐๐โ
If you liked the article, consider subscribing to Cloudaffle, my YouTube Channel, where I keep posting in-depth tutorials and all edutainment stuff for ssoftware developers.