goredwards
goredwards

Reputation: 2494

why don't javascript object property descriptors always default to false (as per spec)

According to the spec when adding a javascript object property, the following defaults will be applied to property descriptors:

However when assigning an object property using the following (very popular) dot notation method they all default to true.

myObject = {};
myObject.a = 1;

Why is this?

Upvotes: 1

Views: 212

Answers (2)

Elugens
Elugens

Reputation: 22

This is an issue that confuse a lot of new developers/programmers/engineers. There are two methods that contribute to this issue in the MDN. If you look at the Object.getOwnPropertyDescriptor() method in the MDN. It says that writable, enumerable, and configurable all default to false, but when you use the method all will return true (Yes, they are false by default).

Example:

let user = {
  name: "John"
};

let descriptor = Object.getOwnPropertyDescriptor(user, 'name');

console.log( JSON.stringify(descriptor, null, 2 ) );
/* property descriptor:
{
  "value": "John",
  "writable": true,
  "enumerable": true,
  "configurable": true
}
*/

Now, If you use the Object.defineProperty() method then you will see that the special property attributes are set to false by default. In the example below you will notice, because I didn't set an special attributes all of the properties are false by default.

Example:

let user = {};

Object.defineProperty(user, "name", {
  value: "John"
});

let descriptor = Object.getOwnPropertyDescriptor(user, 'name');

console.log( JSON.stringify(descriptor, null, 2 ) );
/*
{
  "value": "John",
  "writable": false,
  "enumerable": false,
  "configurable": false
}
 */

I know this is confusing for most people that are new to JavaScript, but I wouldn't try to overthink it. Keep it Simple...

Upvotes: 0

goredwards
goredwards

Reputation: 2494

Apparently - again according to a non-obvious part of the spec - it is due to the way the object property is defined. See here


If an object property is defined using the dot notation method:

var myObject={}; 
myObject.a=1; 

then all property descriptors default to true


If an object property is defined using the bracket notation method:

var myObject = {};
myObject["a"] = 1;

then all property descriptors default to true


However if an object property is defined using the defineProperty method:

var myObject={}; 
Object.defineProperty(myObject, 'a', { value: 1 });

any undefined descriptors default to false.


See an example in this jsfiddle

Upvotes: 0

Related Questions