5/6 Defining a function


in defining a function what does this second line serve for?

function search (lastName) {
var contactsLength = contacts.length;



First read

= = = = = = = = = = = =

In the exercise you created a contacts Array
var contacts = [bob,mary];
giving you an Array with 2 Elements contacts[0] and contacts[1]
both element's are of the type object.
contacts.length => 2 will give you the first-free-index-nr, and is undefined
it is therefore that you declare i = 0 and use the condition i < contacts.length to get at all of your Array-element's in a FOR-loop.

You can also use the length property when you want to add an element like
contacts[contacts.length] = peter; ( peter being a newly defined object )
contacts.length would now be 3.


Correct me if I misinterpret @pislarm's question, but did you mean "what's the purpose of creating a variable for the length of the contacts array when you can simply write 'contacts.length' in the limit of the for loop?"

I've tried it without the variable contactsLength and my for loop looked like: for (var i = 0; i < contacts.length; i++) and it worked just fine.

Is there a reason to declare contactsLength in the function? Is it a way to prevent discrepancies between global and local variables, or is it just for simple exercise?


yup that's exactly was i was thinking, still haven't found the reason though... thanks for both answers anyway!