6. We Made A Friend


#1

Here is 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 (var i = 0; i < contactsLength; i++) {
if(lastName === contacts[i].lastName) {
printPerson(contacts[i]);
}
}
}
//search("Jones");
function add(firstName, lastName, email, phoneNumber) {
var contacts[contacts.length] = {
firstName: firstName,
lastName: lastName,
email: email,
phoneNumber: phoneNumber
};
};
add("james","hetfield","619-444-7777","singer@yahoo.com");
list("james");

It gives me: "SyntaxError: Unexpected token ["

I don't think I am understanding why.

Could someone help me understand and identify the problem in my code?


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

Hello, just a helpful tip. It's much easier to read your code whenever it is indented.

You're trying to redeclare a gloabal variable of the array again inside of your add function, so you would want to change it to something like this:

contacts[contacts.length] = { ... };

Really close, but I believe that's your problem.

Also, whenever you're calling your list function you do not need to put a parameter. It is simply used to return all the contacts in the array. Not a specific one like the search function.

So, instead of
list("james");
It would be fine as just
list();


#3

also remove the word "var" in front of contacts "var contactsLength = contacts.length; "
I don't know why, but it worked for me a few lessons ago....