#4 Listing Everybody


Hi Everyone, 
my questions is pretty simple.  In this exercise we are asked 
" define a variable to store the number of items in the contacts 
array. "

I believe I get it
  var contactsLength = contacts.length;

My question is: what is the reason for defining the variable 
contactLength, will there ever be any difference vs. the code below.

  for (var i = 0; i < contacts.length; i++) {};



HI there aren't any difference between the two.


Thank you,
Would there ever be any benefit to adding the extra line?


If requesting the length involves counting each element then it would be faster to only do it once and store the result.

Whether that's the case depends on the data structure, for an array for example it's probably just a value that's stored and updated when things are added/removed (I barely know any js so no promises)

Even if it's a stored value that is fast to look up, it may take longer to look up a field inside an object than to read a local variable.. And that's language and implementation-dependant so again, no promises.

Bottom line:
- Very likely slightly faster to create a name for it.
- Most likely the difference will be very small and it it takes second place to whatever is just more readable.
- For certain data structures it can be MUCH slower to request it repeatedly.


If you go further in exercise "We made a friend" where you will see you need contacts.length again to use in "add" function. However, if you want to use contactsLength inside the add function without declaring (var contacts.length = contactsLength)it again it will not work. Everything's logical but why it's not working!!

Then that question will give you an idea what is local variable and global variable. You will get to know about these local and global variable later in the next few exercises. I somehow think its there may be to give you the answer of global/local variable later on.