6. We Made A Friend!...it works, but HOW?


How does the function know what to substitute?

When I give my add function an attributes like "Mike" for the firstName, how does it know to substitute it like this:

firstName: "Mike"

and NOT like this:
"Mike": "Mike"

(after all, the declaration is firstName: firstName)

From: https://www.codecademy.com/courses/building-an-address-book/0/6?curriculum_id=506324b3a7dffd00020bf661#

/* creating the add a friend function */
function add(firstName, lastName, phoneNumber, email) {
    contacts[contacts.length] = {firstName: firstName, lastName:lastName, phoneNumber:phoneNumber, email:email }

add("Michael", "Bluth", "(904) 988 8778", "mike@bluth.co");

Someone, please help!


In the above, firstName: is the key name for the new object. firstName is the parameter variable that holds the name, 'Michael' that was passed into the function. The key names are common to all objects referenced in the contacts array. Their data will be unique to each reference.

firstName:  is defined as the value held by the variable, `firstName`

so the object then will look like this:

var index = 2;

// { firstName: 'Michael', lastName: 'Bluth', phoneNumber: '(904) 988 8778', email: 'mike@bluth.co' }


Do I understand your explanation correctly, that this is just the standard behaviour. I.e. whenever it's an object within a function, the bit that looks like a parameter variable, but has the colon after it, will always be treated as a key, and not a parameter variable?


That's correct. The key is a 'symbol` of sorts, similar to Ruby hashes, or Python dictionaries. The parameter variable's value is assigned to the object member named by the key.


Thank you very much for your help!


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