Problems with dot notation inside function definition


#1

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

TypeError: Cannot set property 'firstName' of undefined


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"*/
var search = function(lastName){
    var elementos=contacts.length;
    for (i=0;i<elementos;i++){
        if (contacts[i].lastName===lastName){
            printPerson(contacts[i])
        }
    }
};
search("Jones")
var add=function(firstName,lastName,email,phoneNumber){
    contacts[contacts.length].firstName=firstName;
    contacts[contacts.length].lastName=lastName;
    contacts[contacts.length].email=email;
    contacts[contacts.length].phoneNumber=phoneNumber;
};
add("Pepe","pérez","pepeperez@gmail.com","5555555")
list()


don´t know at all why it doesn´t work when trying to define the properties inside the object with dot notation in stead of with { property:value, }
thanks for help.


#2

Ok, so you want to add new properties to the object. So in the first place you will need the object to work on.

You have to assign to the contacts[contacts.length] empty object and now you can add properties to it:

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

#3

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