Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I created this object and it's 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 then I call a for loop on them:

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

Which according to my tutorial, should produce the following results:

value
name

But instead it only displays value. Why is name not showing up?

like image 830
FairyQueen Avatar asked Apr 17 '12 03:04

FairyQueen


People also ask

How FOR loop is executed in JavaScript?

To execute this loop, the Start condition is checked. This is usually the initial value where the counting should start. Next, the Condition is tested; this test determines whether the loop should continue. If the test renders a true result, then the Expression is used to modify the loop and the Statement is executed.

What is a for in loop for properties?

In JavaScript, the for-in loop is a basic control statement that allows you to loop through the properties of an object. The statements of code found within the loop body will be executed once for each property of the object.


2 Answers

The default value for enumerable in defineProperty is false; non-enumerable properties do not show up in for…in loops. (That's the whole point of the enumerable flag.) If you add enumerable:true into your second definition also, it will 'fix' it.

See some docs.

like image 70
Phrogz Avatar answered Oct 29 '22 11:10

Phrogz


Because the name property is not defined as enumerable, set the name definition to

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

and it will show up.

like image 33
pradeek Avatar answered Oct 29 '22 11:10

pradeek