Difference between [key] and .key?


#1

var friends = {};

friends.Steve = {
firstName:"Steve",
lastName:"Josef",
number:45,
address:["Obama Avenue 3440","Denver"]
};

I can see why this code works works:

console.log(friends.Steve.firstName) = Steve
console.log(friends.Steve.lastName) = Josef

But I dont understand why this code produces only undefineds (4 of them)?
for (var key in friends.Steve)
{
console.log(friends.Steve.key)
}

= undefined


#2

Execute this code:

for (var key in friends.Steve) {
    console.log(key);
}

Value of key is a string. And that's true that you can do friends.Steve.firstName, but this is what you are trying to do in the for loop:

friends.Steve."firstName"

And this is the problem. But friends.Steve["firstName"] is completely correct.


So, dot notation usually looks better and is just more natural for us. But bracket notation lets us use a string representing a name of the property to retrieve the value.


#3

@methodsolver81186

++++ the object as an associative array
++++++++++++++++++++++++++++++++
They were taking a line out of the
developer.mozilla.org manual, look here subject::
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

[[ Begin of quote ]]
Properties of JavaScript objects can
also be accessed or set
using a bracket-notation. ( this in contrast to the = literal-notation = )

Objects are sometimes called associative arrays,
since each property is associated with a string value ( call it the property-key )
that can be used to access it.

Having a myCar object like:

 var myCar = {
          make: "Ford",
         model: "Mustang",
           year: 1969
        };

for example, you could access the properties of the myCar object as follows:
myCar["make"] = "Ford";
myCar["model"] = "Mustang";
myCar["year"] = 1969;
[[ End of quote ]]

The 3 possibilties to get access to the property VALUE

1 Via the so-called DOT-notation, here you use the

literal-property-key-name (NO variable-name allowed)
like:
myCar.year ==wil give you the associated number-VALUE => 1969

2 Via the so-called bracket-notation...

2a ---

We use the literal-property-key-name-as -a-string in brackets
myCar["year"] ==wil give you the associated number-VALUE => 1969

2b ---

We declare a variable which has the property-key-name-as -a-string
assigned to it... like:
**var theKey = "year";
myCar[theKey] ==wil give you the associated number-VALUE => 1969
( They also call this, getting at the -associated- VALUE by reference )


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.