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.
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