4. Listing Everybody. Phone Book - question



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++) {


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++) {

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



Awesome. That makes sense. Thanks, stetim.