I'm stuck on 6. We Made a Friend


#1

I'm stuck here's my code;

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(q = 0; q < contactsLength; q++)
    {
        if(lastName = contacts[q].lastName)
        {
            printPerson(contacts[q]);
        }
    }
}

search("Jones");





function add(firstName, lastName, email, phoneNumber)
{
    newContact = new Object();
    newContact.firstName = this.firstName;
    newContact.lastName = this.lastName;
    newContact.email = this.email;
    newContact.phoneNumber = this.phoneNumber;
    
    contacts[contacts.length] = newContact;
}

add("Red", "Liquid", "Redliquid@gmail.com", 025250666);
list();

#2

@jimmy.bush,
Always use the var keyword in your FOR-loop

for(var q = 0; q < contactsLength; q++)

== guidance ==
www.crockford.com
http://javascript.crockford.com/code.html <---JavaScript code-convention
http://javascript.crockford.com/survey.html


#5

@leonhard.wettengmx.n While that is one problem, I don't think that's the specific problem in the OP's case (he isn't using strict mode so the code would work, though not up to proper standards). I think that's the add function causing him problem:

function add(firstName, lastName, email, phoneNumber)
{
    newContact = new Object();
    newContact.firstName = this.firstName;
    newContact.lastName = this.lastName;
    newContact.email = this.email;
    newContact.phoneNumber = this.phoneNumber;
    
    contacts[contacts.length] = newContact;
}

@jimmy.bush You are using this.firstName, but that way of writing is only used when you are using constructor functions. Here, you are creating a new Object and assigning it properties. So, the work of this.firstName has already been done by newContact.firstName. Now, coming to the value that needs to be assigned to, newContact.firstName, it has to be the value supplied through arguments, which is firstName. We don't need this to refer to arguments. Thus the correct code would be:

function add(firstName, lastName, email, phoneNumber)
{
    newContact = new Object();
    // all without this
    newContact.firstName = firstName; 
    newContact.lastName = lastName;
    newContact.email = email;
    newContact.phoneNumber = phoneNumber;
    
    contacts[contacts.length] = newContact;
}

I hope I explained that thoroughly! :slight_smile:


#6

var newContact=new Object();