Javascript Non enumerable property

Javascript Non-enumerable property is used when you do not want to reassign the value of the key of the object. The non-enumerable property of the object does not show when you iterate through the object using for…in loop or using Object.keys() to get an array of property names.


var employee = {
  name: 'John'
};
employee.salary = '$2000';
employee['country'] = 'USA';

console.log(Object.keys(employee)); // ['name', 'salary', 'country']

As we know that employee object properties name, salary, country are enumerable hence it’s shown up when we called Object.keys(employee).

How to create non-enumerable property of the object?

To create a non-enumerable property we have to use Object.defineProperty() and defined enumerable:false. This is a special method for creating a non-enumerable property in JavaScript.


// Create non-enumerable property
Object.defineProperty(employee, 'phoneNo',{
	value : 3333333333,
	enumerable: false
})

console.log(Object.keys(employee));
Output:- [‘name’, ‘salary’, ‘country’]

Note:- phoneNo is not showing in the output because it is a non-enumerable property.

Now let’s try to change value of phoneNo


employee.phoneNo = 4444444444; 
console.log(employee.phoneNo);
Output:- 3333333333

Note:- phoneNo value will not change and show old value.