Can someone explain Exercise 6.7?


#1

TL:DR: can someone explain (3) and (4) to me, below?

Totally stuck on 'Search for a Friend' Exercise 6.7 in Javascript. I have to say that the instructions/hints offer very little explanation at all of the syntax and logic here!

After basically cutting and pasting from the forums, plus some trial and error, I got a code that passes the checks. But I have no idea why this code works, nor why, on calling the function, I get the whole entry for 'Bill' printed rather than just 'Bill'?

Partly, I've been getting totally mixed up because people seem to name new variables with the same name given to objects or keys - e.g. 'firstName'. But we also have some new syntax introduced here which hasn't been explained - the 'friends[ ].firstName' business.

As far as I get it, the code below 'works' because it
1) Creates a function, where you feed it a text string which is 'the Value We Are Looking For' ('theVWALF').

2) Searches through every value in the 'friends' array, and, as it arrives at each value in turn, copies that to a new variable we've created specifically so we can remember it while we compare it to something else. I've called this variable 'theVWF' - 'the Value We Found' - because in the examples provided, people tend to call this 'firstName' or something which just really confuses me.

3) We then get a piece of new syntax I don't understand which we then compare to 'the Value We Are Looking For'. I imagine that the '.firstName' bit is there because we don't just want to means that we are looking for any value in the whole array that matches the bit of text we've given it. We only want people whose first names are Bill - i.e. those values with the 'firstName' key attached to them. Otherwise, I might get 'Buffalo Bill', whose surname is Bill, or someone who lives at 136 Bill Street.

So I'm guessing that .firstName is what we need to make sure that the Value We Found ('theVWF') also has a 'firstName' key attached to it.

Is that right?

4) If we find that the Value We Are Looking For ('theVWALF') matches the Value We Found ('theVWF'), we then print and return the Value We Found. I don't understand why, in this case, we don't just get 'Bill' printed, though. We've been cycling through each value inside each array the database, right? Not just looking at the names of the arrays themselves. So why does it print the whole array?

Code follows. Massively grateful for help clearing this up.


var search = function(theVWALF) {            //the Value We Are Looking For
    for (var theVWF in friends) {                   //The 'Value We Found'
        if (friends[theVWF].firstName===theVWALF) {
            console.log(friends[theVWF]);
            return friends[theVWF];
        }
    }
}. 

search("Bill")


#2

@gigarockstar49577,

   var james = {
        job: "programmer",
       married: false,
       sayJob: function() {
              // complete this method
              console.log("Hi, I work as a" + this.job);
        }
     };

Description of the james object.
The james object has 3 properties which are seperated by a comma-,

there is a job property with property-key job and it's associated string value 'programmer'
there is a married property with property-key married and it's associated boolean value false
there is a sayJob property with property-key sayJob and it's associated anonymous function VALUE
( they also would 'say', the james-object has the sayJob()-Method )

access via dot-notation

james.job ==> you will get the associated string VALUE of the job property-key, thus
you get the string VALUE 'programmer'

james.married ==> you will get the associated boolean VALUE false

james.sayJob ==> you will get the associated anonymous function VALUE
to call/execute this method you add a pair of parenthesis-( )
james.sayJob();

access via the square-bracket-notation

1 using the literal property-key

james["job"]
james["married"]
james["sayJob"]()

2 using the property-key by reference (=== via a variable )

var propertyKey1 = "job";
var propertyKey2 = "married";
var propertyKey3 = "sayJob";
james[propertyKey1] ==> you will get the associated string VALUE of the job property-key, thus
you get the string "programmer"

james[propertyKey2]
in this case you will get the boolean VALUE of the married property
being false

james[propertyKey3]();
would =display= "Hi, I work as a programmer"


#3

@gigarockstar49577

+++ friends list and search and for-in explained.
Look here for an explanation
object
function
for-in-loop
list-function
search-function
http://www.codecademy.com/forum_questions/545275fd8c1ccc8e3e000a23#comment-5457b12c9c4e9d87cb00003f


#4

The search function you build, will purely look for any matching first name, so obviously the object should have a first name property, otherwise it will simply be skipped.

  1. Which array? bill and steve (and more, if you created more) are objects, not arrays. As you can see if you run this code:

console.log(friends);

either way, friends[theVWF] will access the dictonary of bill (or steve, depending at which point in the loop we are), and print the whole dictonary


#5

leonard.wettengmx.n: very comprehensive and helpful. The dot notation and square bracket syntax was actually explained in the following javascript tutorial on objects - once I'd gone through that.

stetim94: Thanks for responding. I thought arrays were types of object - mainly because the way you create an associative array looks identical to one of the ways you construct objects. For example, in the following, 'bob' could be both an associative array, and a new object.

'''

var bob = {
firstName: "Bob",
lastName: "Jones",
phoneNumber: "(650) 777-7777",
email: "bob.jones@example.com"
};

'''

Anyway, leaving that terminology confusion aside, I think I've figured it out - I thought the code was combing through each property of each object in the friends array. It isn't, right? It isn't going through all the properties of those objects - it's just checking the property called 'firstName' that belongs to each object, to see if it matches the Value We Are Looking For.

Then it returns the whole object ('bill' or 'steve'). If I wanted it to just return the first name I'd have to write

'''

return friends[theVWF].firstName;

'''

That would print e.g. 'bill' for each time the first name 'Bill' appeared in my contact book. Not exactly the point of the exercise, though.

Hope that's all correct.


#6

So we have to use one of JavaScript's minor mysteries.
In JavaScript, objects are also associative arrays

Seems you are right, javascript can be confusing. It also explain why can do both:

friends.bill.firstName

which is the object notation, and:

friends["bill"].firstName

which associative array notation

Yep, you seem to understand it now. I admit, it can be confusing.


#7

@gigarockstar49577
++++ 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 )