# Question regarding 6. We Made a Friend

#1

I was completing this excersize, and I was wondering, what is the advantage of using the shown method to solve this problem, over using the method "array.push".

``````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]);
}
}

function search(lastName) {
let contactsLength = contacts.length;
for( var i = 0; i < contactsLength; i++) {

if(contacts[i].lastName === lastName) {
printPerson(contacts[i]);
}
}
}

function Person(firstName, lastName, phoneNumber, email) {
this.firstName = firstName;
this.lastName = lastName;
this.phoneNumber = phoneNumber;
this.email = email;
}

var darren = new Person("Darren", "Styles", "780-405-1234", "darrenStyles@gmail.com");
contacts.push(darren);

list();

function add(firstName, lastName, email, phoneNumber) {
contacts[contacts.length] = { //Adds an object to the end of an array
firsName: firstName,
lastName: lastName,
phoneNumber: phoneNumber,
email: email
}
}

list();``````

#2

If you're referring to why you write `var contacts = [bob, mary];` instead of pushing them in its because in this case when you're defining your array you already have the data you want to store in it so you put them in at initialization.

If down the road you met someone new and wanted to add their contact info to the `contacts` array that would be a good time to `contacts.push(Chrinkus);`.

EDIT: My bad, that's exactly what's happening here. YES, you should be using `contacts.push()` here. But the current course does not delve too deeply into the `Array.prototype` methods so they get you to do pretty much what `arr.push()` does anyway.

Other resources often have you manually write `arr.map()`, `arr.filter()`, etc and such before you use the actual methods so its still good to learn HOW these work.

#3

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