5/6 Finding that Special Someone


#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"*/
var search = function(lastName){var contactsLength = contacts}

for(var i = 0; i < contacts.length; i++){ if(lastName === contacts[i].lastName) {printPerson(contacts[i]) } }

search("Jones");

I passed this exercise. However, I'm wondering if I should have. If I call the search function with the word "Jones," it works and prints out the name Bob Jones. However, if I call the search function with "Johnson" just to experiment, it still prints out Bob Jones! What is wrong with my code?


#2

I think this fixed it:

var search = function(lastName){var contactsLength = contacts; for(var i = 0; i < contacts.length; i++){ if(lastName === contacts[i].lastName) {printPerson(contacts[i]) } } }

search("Jones");

Does it really matter that the for loop appear in the body of the function rather than after it?


#3

Definitely, it does matter. That's the functional code of the function. Outside of the function it will not run at all. Expect a ReferenceError.

meant to be,

contactsLength = contacts.length

#4

Okay, here's another question:

I'm assuming this is the right way to do this exercise based on the directions: var search = function(lastName){var contactsLength = contacts.length; for(var i = 0; i < contactsLength; i++){ if(lastName === contacts[i].lastName) {printPerson(contacts[i]) } } };

Why couldn't I just eliminate the variable contactsLength and just use contacts.length in the parameters of the for loop? I tried that and the program still worked. So the code would be var search = function(lastName){for(var i = 0; i < contacts.length; i++){ if(lastName === contacts[i].lastName) {printPerson(contacts[i]) } } };


#5

Aside: It would be nice to be able to read your code in formatted form. It should look like this,

var search = function (lastName) {
    for (var i = 0; i < contacts.length; i++) {
        if (contacts[i].lastName === lastName) {
            printPerson(contacts[i]);
        }
    }
};

The variable you ask about is only expected in the lesson that introduces it. Your intuition is correct that it is unnecessary. Normal practice is to use the length property directly. There are instances where the starting length may need to be compared to the ending length if an array is changing inside the loop (pop, push, shift, unshift) but there is no real reason to bring this up now.