Sudharsan S
Sudharsan S

Reputation: 15393

delete operator - behave's strange

Could anyone explain what is own non-configurable property and non-strict mode?

Don't know the scenario it confuses me a lot. In my knowledge the delete operator removes a given property from an object. On successful deletion, it will return true, else false will be returned.

In the below example

var Employee = {
  age: 28,
  name: 'abc',
  designation: 'developer'
}

console.log(delete Employee.name)   // returns true
console.log(delete Employee.age)    // returns true
console.log(delete Employee.salary) // returns true

The employee object has both the properties name and age. but didn't contain the property salary. If when trying to delete a unknown property salary all of them included me assume it is returned false or may be undefined but they returned also true if the property does not exist in the object but it returns true. How??? I couldn't understand this behavior.

Upvotes: 0

Views: 85

Answers (2)

Dave Newton
Dave Newton

Reputation: 160181

That's not what delete returns.

true for all cases except when the property is an own non-configurable property, in which case, false is returned in non-strict mode.

That's just the way it works. "Non-configurable property" is the key phrase.

To expand on what epascarello states, MDN explicitly states:

If the property which you are trying to delete does not exist, delete will not have any effect and will return true.

MDN also has a whole bunch about strict mode.

Documentation is your friend (at least in this case).

Upvotes: 0

OliverRadini
OliverRadini

Reputation: 6467

As others have said, delete will only return false for non-configurable properties. An example of such a property would, for the data you mentioned in your question, be Employee.name.length, on which delete would be false.

Non-configurable properties can be created, if you're interested you can read more here:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#Modifying_a_property

From the above link, you can see how you can setup properties to be configurable (or not):

Object.defineProperty(o, 'b', {
  get: function() { return bValue; },
  set: function(newValue) { bValue = newValue; },
  enumerable: true,
  configurable: true
});

Upvotes: 1

Related Questions