Why is my for loop not working on my Javascript properties?

I created this object and its properties:

var obj = {};

Object.defineProperty( obj, "value", {
  value: true,
  writable: false,
  enumerable: true,
  configurable: true
});

var name = "John";

Object.defineProperty( obj, "name", {
  get: function(){ return name; },
  set: function(value){ name = value; }
});

So, I find a for loop for them:

for ( var prop in obj ) {
  console.log( prop );
}

According to my study guide you should get the following results:

value
name

But instead, it displays the value. Why doesn't the name appear?

+5
source share
2 answers

The default value for enumerableis definePropertyequal to false; Invalid properties are not displayed in loops forโ€ฆin. (This is the whole point of the flag enumerable.) If you add enumerable:trueto your second definition, it will โ€œcorrectโ€ it.

See several documents .

+6
source

name ,

Object.defineProperty( obj, "name", {
  enumerable: true,
  get: function(){ return name; },
  set: function(value){ name = value; }
});

.

+5

All Articles