Why create the var contactsLength?


#1


https://www.codecademy.com/courses/building-an-address-book/0/5


Hi Y'all!

I am not really stuck or anything but I am wondering why the exercise asks me to create the variable contactsLength instead of just puting contacts.length in the loop.
That is what I did for the exercise anyway and it worked but I don't see the purpose of this variable - to me it just looks like extra work.

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

If you have an explanation I'll be glad to read it.
Thanks.


#2

The less you iterate through the DOM or in this case the list of contacts ,i suppose , the more efficient your code is. In this case the variable contactsLength holds the length only a single time and every time the loop runs the value of length is picked up from this variable to check whether
i
is less than the value of length no matter how many times the loop runs. It is a very good practice to keep values inside a variable and use them later, esp when using under a loop.

hope that helps...


#3

Oh ok, I did not think about that.
Thanks for the enlightenment.


#4

welcome :slight_smile:


#5

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