Why define the number of items in contacts array?


#1



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


Curious as to why the exercise wants us to define variable "contactsLength" to store number of items in contacts array when we could just use For loop and calling printPerson to do the job.
Any particular reasons?
Thanks for any reply in advance!


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

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


#2

In any typical for-loop:

for(declaration; condition; update){

}

the condition is checked at every iteration of the loop.

Now imagine if this loop had ten thousand iterations, wouldn't it be reasonable to store the length of the array as a separate variable so we don't need to access it (...using the dot operator - contacts.length) at every iteration. This will help us optimize our code and reduce its running time.