Quilty Kim
Quilty Kim

Reputation: 463

how do javascript objects constructed with both dot and literal notation behave when called?

While running the code below, without any function calls, I would immediately get this output

["1122","3rd St","Seattle","WA","92838"]

The closest thread that addressed this code was Need Explanation: Organization with Objects in a Contact List (Javascript, Codecademy) but it didn't quite address my concern.

I'm sure that the way I had added key,value pairs to the objects is somehow yielding this output, but I can't seem to explain why, especially when running the code, there is no function call included.

When actually trying to call search (e.g. search("steve")), it would fail but it would work on search("bill"). I thought it might be related to the javascript console but I checked using Chrome's console with the same results. Any help would be much appreciated.

var friends={};
friends.bill = {};
friends.steve={};
friends.bill["firstName"]="Bill";
friends.bill["lastName"]="Gates";
friends.bill.number="333.222.3937";
friends.steve["firstName"]="Steve";
friends.steve.lastName="Ballmer";
friends.steve["number"]="829.383.3939";
friends.bill["number"]="232.8392.2382"
friends.bill.address=['5353','Cook Ave','Bellevue','CA','94838']
friends.steve.address=['1122','3rd St','Seattle','WA','92838']


    var search=function(name)
    {
    for(var i in friends){
        if (name==i["firstName"])
    {
        console.log(friends[i])
        return friends[i]
    }
        else{
            return "no match"
        }

    }
}

Upvotes: 0

Views: 72

Answers (2)

masahji
masahji

Reputation: 544

You are seeing this output:

["1122","3rd St","Seattle","WA","92838"]

Because it is what is currently stored in $_ (Most browser based JS interpreters will spit out what is in $_ on the prompt).

$_ is the value of the last evaluated expression, which in your case is:

friends.steve.address=['1122','3rd St','Seattle','WA','92838']

The "var search ..." is actually a declaration and will therefore not be stored in $_.

Also, your search function should probably look like this:

var search = function(name) {
  for(var i in friends) {
    if (name.toLowerCase() == friends[i]["firstName"].toLowerCase()) {
      console.log(friends[i])
      return friends[i]
    }
  }
  return "no match";
};

@cherniv might have beat me to the punch on moving the return out.

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100205

try changing:

for(var i in friends){
    if (name==i["firstName"])
        ...

to

for(var i in friends){
    if (name == friends[i]["firstName"])
        ...

You meant something like:

for(var i in friends){
    if( name == i ) { //i would be either "bill" or "steve" and check against name variable
        console.log("Data for:" + i + " firstname is:" + friends[i]["firstName"]);
    }
}

Upvotes: 2

Related Questions