Some Unseen Object Attributes in Javascript
Enumerable, Writable and Configurable
Have you heard about Enumerable, Writable and Configurable attributes.
if yes, You can look into some interesting stuff here
else lets dig deeper into these attributes of an object.
Have you ever given a thought why hasOwnProperty, get, set etc ... properties are not iterable.
Here is the answer for you.
// code
myObj = { website: "karthik.bio" };
Object.defineProperty(myObj ,"email",{
value: "me@karthik.bio",
enumerable: false // default value is true
});
for(key in myObj) {
console.log(`${key} - ${myObj[key]}`)
}
// output
website - karthik.bio
In the above code I have created an object named myObj and added website property to it. This is normal way of adding a key to any object.
In the next line I have created one more property Using Object.defineProperty
Object.defineProperty accepts object, name of the property to be added and its attributes like value respectively.
Note: -The output is only website - karthik.bio
I hope By the time you reach here you understand what is enumerable.
The Enumerable attribute controls list of properties that will appear in various enumerations of object properties. such as Object.keys(..)
, Object.entries(..)
, for..in loops
, and ...
object spread.
Do you wanna Make a property Read Only
In the Object.defineProperty(..)
method just pass writable as false and configurable as false and that property can become read only. We can't reassign any value to that property using neither =
operator nor Object.defineProperty(..)
, writable
restricts only the usage of =
operator while configurable
restricts the Object.defineProperty(..)
. However if any of the attribute is true then we can reassign the value either by using =
operator or Object.defineProperty(..)
Example Code
myObj = {};
Object.defineProperty(myObj ,"name",{
value: "Karthik Minnikanti",
writable: false // default value is true
configurable: false // default value is true
});