Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Object.defineProperty check if the property is defined?


I need to define property for a javascript object.
var obj = {};
obj['prop1'] = 1


In the above way, we can define the property.
Now, let us use Object.defineProperty
var obj = {}; Object.defineProperty(obj,'prop1',{value:1});
this is alternate way.

what is the difference between the two?
Does Object.defineProperty check if the property is already defined or not??
I believe obj['prop1'] = 1 checks for the property
thanks :)

EDIT
Any performance variation in between those?

like image 591
Navaneeth Avatar asked Nov 21 '25 12:11

Navaneeth


1 Answers

Neither a direct object access, nor Object.defineProperty will "check" for existing properties. The only difference between those two is the possbility, to modify property descriptor values.

Property descriptors are

  • enumerable
  • configurable
  • writable

which are all set to true by using direct property access. With Object.defineProperty you have the option to set these properties individually. I suggest you read this MDN article to get an idea about the meanings.

If for instance, a propertie owns the flag configurable=false, you cannot overwrite or delete it (which might be the case for your issue).


Concerning performance:

Since Object.defineProperty is a function which needs to get executed each time, it has to be slower than a direct access on the object. I created this little benchmark:

http://jsperf.com/property-access-with-defineproperty

However, even if the difference looks drastically, you may not forget the value and reason for Object.defineProperty.

like image 99
jAndy Avatar answered Nov 23 '25 02:11

jAndy