1

So I have this javascript object, and I want to loop through and print out each of it's property values.

Here's the code:

var names = {
            "firstName":"Billy",
            "lastName":"John",
            "age":30
        };

for(var a in names){
    console.log(names.a);
}

And it console.logs "undefined" 3 times.

But if I do something like this:

for(var a in names){
    console.log(names[a]);
}

It prints out Billy, John, 30.

If I console.log names.firstName outside the loop it works. And considering that during the first loop execution a is firstName, it should work.

Why does this happen? Thanks.

bool3max
  • 2,748
  • 5
  • 28
  • 57

4 Answers4

2

Because names does not have a .a property. a refers to a variable whose value is the property.

caasjj
  • 1,354
  • 8
  • 11
2

names[a] and names.a are not equivalent.

a is a variable that references a string.

names.a expects a key named a in your names object.

names[a] equates to each of names.firstName, name.lastName and names.age.

Adrian Lynch
  • 8,237
  • 2
  • 32
  • 40
2

Because using dot notation (names.a) you are accessing the property a on your object, this property is of cause undefined.

When you use bracket notation names[a] then the variable will be evaluated and the statement will look like this: names['firstName'], names['lastName'], ...

Normally you would always use dot notations when accessing properties, but in your case - because you need to access the property with the name the variable holds - you will need to use bracket notation.

Another scenario you would use bracket notation is when you will need to access a property that have a name that cannot be written using dot notation. Consider this:

var a = { "my-special property": 1 };
// Try to access it via dot notation:'
console.log(a.my-special property); // SyntaxError
// But with bracket notation:
console.log(a['my-special property']); // 1
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
1

If you wrote:

var names = {
            "a":"property a",
            "firstName":"Billy",
            "lastName":"John",
            "age":30
        };

Then the loop:

for(var a in names){
    console.log(names.a);
}

would log property a three times, understand?

Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100