user4493534
user4493534

Reputation:

Why does this JS for-in loop log just the key of a property, and not the entire property?

MDN says:

The for..in statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.

If I put in this JavaScript code:

var myObject = {0:'cat', 1:'dog', 2:'fish'};

for (var x in myObject) {
    console.log(x);
}

I get this ouput:

0
1
2

If it is iterating "over the enumerable properties", why does it not log the entire property, like this?

0: 'cat'
1: 'dog'
2: 'fish'

I realize I could have it log the values as well, via myArray['x'], but I'm wondering why it only logs the keys as it is.

Is this simply part of the built-in logic of for-in loops, and relates to their intended uses?

Upvotes: 0

Views: 51

Answers (1)

bhspencer
bhspencer

Reputation: 13570

That is the intended behavior of the javascript for in loop. If you want the value of the property then you should do this:

var myObject = {0:'cat', 1:'dog', 2:'fish'};

for (var x in myObject) {
    console.log(myObject[x]);
}

In your example object you have three properties. The names of those properties are 0, 1 and 2. The values of those properties are "cat", "dog" and "fish". For in loops enumerate the names of the properties not the values.

Upvotes: 4

Related Questions