What is enumerable in javascript
Javascript is dynamic in nature so we can freely modify behaviour and property of objects.
Example
let data = {name: ‘Shivam Gupta’}
we can do anything with data like — adding new key / remove key or modify existing data like — data.name = “xyz”
But in some cases if we want to prevent our object so that it can not be modify ?
What enumerable means
It simply means that the property will show up if you iterate over the object using for..in
loop or Object.keys
.
var data = {name:’xyz’}; using for..in loop we can access name so this is enumerable by default
Means we can iterate over object keys if keys are set to enumerable (By default enumerable)
Let's look at one simple example:
ES-6 provides new mechanism so that we can set the given properties for a key inside object —
{
value: "Shivam Gupta",
writable: true,
enumerable: true,
configurable: true
}
- You can make key enumerable — false (So that key will not be access by for..in loop or object.keys)
- You can make particular key readable only by — writable: false
Object.defineProperty method allows us to change the object keys property
Object.defineProperty(objectName, 'key', {
value: 'Value for that key',
configurable: true,
writable: false,
enumerable: false
});
Lets Try simple examples :)
var info = {
name: “Shivam gupta”,
addres: “xyz”,
email:”shivamethical@gmail.com”
}Object.defineProperty(info, ‘name’, {
value: ‘Now Shivam Change’,
configurable: true,
writable: false, // we cant edit name using . operator
enumerable: false // means we can not access this key anymore by for..in loop or object.keys()
});Object.keys(info); //[“addres”, “email”]
So name key cant access.
Lets try to change name by —
info.name = “please change”
but it will not change because of writable: false
Thanks, please write in comment section !