6. We made a friend - Object name?


#1


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

var mary = {
    firstName: "Mary",
    lastName: "Johnson",
    phoneNumber: "(650) 888-8888",
    email: "mary.johnson@example.com"
};

var contacts = [bob, mary];

function printPerson(person) {
    console.log(person.firstName + " " + person.lastName);
}

function list() {
	var contactsLength = contacts.length;
	for (var i = 0; i < contactsLength; i++) {
		printPerson(contacts[i]);
	}
}

/*Create a search function
then call it passing "Jones"*/
function search(lastName){
    var contactsLength = contacts.length;
    for(var i = 0; i<contactsLength; i++){
        if(lastName === contacts[i].lastName){
            printPerson(contacts[i]);
        }
    }
}


function add(firstName, lastName, email, phoneNumber){
    contacts[contacts.length] = {
        firstName: firstName,
        lastName: lastName,
        phoneNumber: phoneNumber,
        email: email
    };
}

add("Eric","Chou","eric@com.com", 123-123-1231);
list();

Okay, my question is what's the name of the object I'm creating? It doesn't make sense to me because for bob and mary I created the objects and named them as so. However, when I'm adding a new contact I'm not adding an object name.


#2

bob and mary may appear to be in the array, but in reality, they are right where they were when they were declared, in memory somewhere. Their identifiers are given location information so the values can be referenced. It's this information that is also in the array for those two objects.

The new contacts on the other hand are anonymous objects created and cached in the array. bob is still bob, but also contacts[0], and mary is still mary, but also contacts[1]. All others are only contacts[i]

Consider for a moment how advantageous an array of objects will be, especially when it is a large array. It is organized, and sortable. A mountain of arbitrarily named objects in any namespace will quickly prove very messy, confusing and cumbersome.


#3

I don't think that's really what he was asking (not to be rude). It is a project that they give you and I am also trying to solve it. The instructions are to make the function that he has made and I have the same exact question, we are not trying to find a better way to put them in an array, we are simply trying to finish the project.


#4

I explained why the author is showing us both ways. The latter, inserting an object directly into an array is the better of the two for the reason given.

If you are having a problem with this lesson then start a new thread of your own, rather than hijacking this one.


#5

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