Ray Stanz
Ray Stanz

Reputation: 81

javascript: datatype of propertyname

Just out of curiosity, when I iterate over an object via for(var p in object), is p a string or something else? I'm initializing variables always with only one statement so I want to make sure the type is right before it is used in the for loop.

Upvotes: 2

Views: 70

Answers (2)

Florian Margaine
Florian Margaine

Reputation: 60727

The value of p is the key. If all the keys of your object are strings, then p will always be a string. If you iterate over a Map, the keys will be objects. It all depends on your object. But yes, most of the times it will be a string. (Chances are, if you're using a Map, you don't need to ask this question.)

The old way to make sure the properties are the enumerable properties is the following:

for (var p in myObject) {
    if (myObject.hasOwnProperty(p)) {
        // 'p' is a key for an enumerable property of myObject
    }
}

The new way, with ES5, is using Object.keys:

Object.keys(myObject).forEach(function(p) {
    // 'p' is a key for an enumerable property of myObject
});

This code requires IE9 or a shim for legacy browsers though. Simply put, Object.keys(myObject) returns an array of the object's keys (for the enumerable properties only).

Upvotes: 3

Aesthete
Aesthete

Reputation: 18848

Yes, the type of p in for(var p in object) is a string.

Using this control structure treats the object as an associative array (really they are the same anyway). The key for each property is assigned to p.

Be aware, that looping through an object like that will give you all enumerable properties, not just the ones you've added to the object, but any that have been inherited from up the prototype chain.

You can limit the property to the ones you've added like so:

for(var p in myObject) {
  if(myObject.hasOwnProperty(p)) {
  }
}

Upvotes: 2

Related Questions