javascript : I could delete the property form object, the property, which is defined as non configurable. Why?

Viewed 35

var obj={};
Object.defineProperty(obj,'test',{value:300,configurable:false});
console.log(obj.test)
delete obj.test
console.log(obj)

'test' property defined as non-configurable can be deleted. But as per my knowledge it should not. Could some please explain why this is happening.

1 Answers

If you had logged obj.test instead of just obj, you'd have noticed that the property is still there and not actually deleted. You have to set enumerable: true in order for the property to show up when logging the object's properties (i.e. the object itself). It's set to false by default.

Logging obj.test with the default, enumerable: false:

var obj={};
Object.defineProperty(obj,'test',{value:300,configurable:false});
console.log(obj.test)
delete obj.test
console.log(obj)
console.log(obj.test)

Logging obj.test with enumerable: true:

var obj={};
Object.defineProperty(obj,'test',{value:300,configurable:false,enumerable:true});
console.log(obj.test)
delete obj.test
console.log(obj)

Related