4. Listing Everybody. Phone Book - question


#1


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


In the instructions we're asked to;
At the start of the function, define a variable to store the number of items in the contacts array. Call it contactsLength.

I didn't completely understand why would we do that so I tried it without it and the code runs. Is this something that might be considered best practices?


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]);
    }
};
list(contacts);


#2

if you create a variable contacsLength, and store the length in here, you only have to calculate the length once:

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

if you do what you did, it has to calculate the length in every run of the loop. It is performance improvement.

source


#3

Awesome. That makes sense. Thanks, stetim.

Kevin


#4