14.6 Why does my second add call override my first


#1


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


After I got the success award- I tried to add another, just because I like to test things- and it overrides my first add call. Any ideas?


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

function add (firstName,lastName,email,phoneNumber){
    contacts[contacts.length]=this
    this.firstName = firstName,
    this.lastName = lastName,
    this.phoneNumber = phoneNumber,
    this.email = email
    };
add("Will", "Franklins", "888-505-5555","Will.Frank@email.com");   
add("Why", "Ewedothis", "666-666-6666","Owned@Code.com");

list();
//returns
//Bob Jones
//Mary Johnson
//Why Ewedothis
//Why Ewedothis


#2

Improper use of constructor syntax. There should be no this object reference in your function. Just direct property value assignments.

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

In the above we are assigning an anonymous object literal to the end element of the contacts array.


#3

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