What is the purpose of storing the length of the contacts array in a variable?


#1

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

My code is working just fine, but I'm just curious why, in Listing Everybody and Finding That Special Someone, we are asked to make a variable and set it to the length of the contacts array. I did it without the variable, just using contacts.length directly, and it worked just as well (and passed). And "contactsLength" isn't really any shorter to type, so what is the reasoning behind using it?

Code with variable:

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

Code without variable:

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

#2

I think the only reason they ask you to do this is to help you form a habit of creating a variable instead of typing contacts.length each time. The idea of this is more efficient but renaming it to a variable exactly the same length makes it inefficient practice. It would make sense if they named the variable x or something.

But regardless of that it is still a good habit to make.


#3

In this exercise, sadly, there is no purpose to that variable that is demonstrated. It seems like the author just wanted us to know that we can cache the length.

The only real purpose to caching is if the value is re-used somewhere else in the program. For instance, in a dynamic setting the length might change from the start of the loop to the end. Comparing the ending length to the starting length would give us a signal that the length has or has not changed. Beyond that, I can see no other real reason in this instance.

Bottom line, we don't need to cache values that are not re-used. Array.length is a property that can be easily polled in the loop parameters. That is the norm. Fortunately, this is the only lesson that asks us to do this, so going forward, park this notion until such time as caching the length of an array makes sense in the program.


#4

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