What is enumerable in javascript

Shivam Gupta
2 min readOct 6, 2018

--

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..inloop 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:

Object.getOwnPropertyDescriptor() — returns an object with the characteristics of the property

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
}
  1. You can make key enumerable — false (So that key will not be access by for..in loop or object.keys)
  2. 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 !

--

--

Shivam Gupta
Shivam Gupta

Written by Shivam Gupta

Full Stack Engineer (Web/App) working on different JS Technologies & frameworks— Angular, Node, Typescript, Ionic, Firebase, AWS, ElK...Love to write cool stuff

Responses (3)