Why create the var contactsLength?



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

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


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
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...


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


welcome :slight_smile:


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