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));
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);
Note:- phoneNo value will not change and show old value.
Javascript Non enumerable property – Interview Questions
Q 1: What is a non-enumerable property?
Q 2: How to create it?
Q 3: Is length enumerable?
Q 4: Can for...in access it?
Q 5: Why use non-enumerable?
Javascript Non enumerable property – Objective Questions (MCQs)
Q1. Non-enumerable properties are skipped by ______.
Q2. Which method defines non-enumerable properties?
Q3. Default value of enumerable is ______.
Q4. Which method lists only enumerable properties?
Q5. Non-enumerable properties can still be accessed using ______.