7. Contact list: questions


#1

Hi Everyone,

I have a bunch of questions here. Lets start with my code:

> var friends = {
>     bill: {
>         firstName: "Bill",
>         lastName: "Gates",
>         number: "(206) 555-5555",
>         address: ['One Microsoft Way','Redmond','WA','98052']
>     },
>     steve: {
>         firstName: "Steve",
>         lastName: "Jobs",
>         number: "(206) 333-3333",
>         address: ['Two Apple Way','Redmond','WA','98052']
>     }
> };


> function list() {
>     for(var x in friends){
>         console.log(x);
>     }
> };

> var search = function(name){
>     for (var x in friends)
>         if( friends[x].firstName === name ){
>             console.log(friends[x]);
>         }
>         else {
>             console.log("No Match!");
>         }
>     }
> };

> search("Bill");
  1. First, what is the difference between var search = function() and function search() ?

  2. Can someone explain my the return action, why does it have to go along with the console.log in this case? A bit confusing.

  3. Following my reasoning, when I create my search function, I am 1) giving it an argument name 2) looping through friends in order to find my friends, e.g "bill" and "steve" 3) setting a conditional and letting accessing my friends objects the firstName property 4) checking if it matches with the search function input (e.g: the name argument, thrown with the search("Bill"); 5) printing in the console the matched friend' name, if not matched, "else".

I can't really understand what's going wrong here.

Thanks in advance,


#2

1) the statement version runs before the rest of the code otherwise it has mostly the same effect
2) printing and returning are different actions, they do not need to go together. printing puts text on the screen, functions return control to their caller when done


#3

@ lonatan, Thanks for the answer.
In the meantime, do you see something wrong with the reasoning above?


#4

Found it! A missing bracket opening my for loop...

Thanks!

var search = function(name){
>     for (var x in friends) {
>         if( friends[x].firstName === name ){
>             console.log(friends[x]);
>         }
>         else {
>             console.log("No Match!");
>         }
>     }
> };

#5

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