Not sure why it worked - We made a friend


Hi guys!

My code below seems to work but there's one thing that I'm not sure of:

In the "for" loop of the "list" function, we set "i" to be < contacts.length, in this case it is < 2, so reasonably we can expect it to run only to the [1] item in the array right? But why can we print out the added object even though the object is "contacts[contacts.length]"? Since in this case contacts[contact.lengths] is contact[2], and I thought it shouldn't be printed because the loop stops exactly at [2] of the array?
Or it is because when we set "contacts[contacts.length]" we extend the array's length automatically?

I found it hard to express in more technical terms :stuck_out_tongue: so I hope my question is clear. Thanks!

var bob = {
    firstName: "Bob",
    lastName: "Jones",
    phoneNumber: "(650) 777-7777",
    email: ""

var mary = {
    firstName: "Mary",
    lastName: "Johnson",
    phoneNumber: "(650) 888-8888",
    email: ""

var contacts = [bob, mary];

function printPerson(person) {
    console.log(person.firstName + " " + person.lastName);

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

function add(firstName, lastName, email, phoneNumber) {
        contacts[contacts.length] = {
        firstName: firstName,
        lastName: lastName,
        email: email,
        phoneNumber: phoneNumber

add("Tommy", "Ling", "", "1-800-345-216");



I'm not sure if I am misunderstanding your question, but...
In the for loop, you set it to stop at contacts.length. As you said, contacts.length would be equal to 2. In computers, array indices work as follows:
0 - > 1st index
1 - > 2nd index
2 - > 3rd index
... and so on ...
So it loops through and prints contacts[0] (first index).
It then increments by 1, and prints contacts[1] (second and final index).
Now i would increment again, but remember....

i < contacts.length

Will stop the loop when i is either going to be equal or greater than contacts.length, so the loops stops.


Hopefully I'm understanding your question and answering appropriately (and using the right terms...)!

If you switch the order you call your add() and list() functions, just as you suspected, it will look through the array, find only bob and mary, leaving off Tommy.

However, because you're calling the list function after you've added Tommy, when printPerson is called by list(), your array already has Tommy added to it. So, fortunately, our new friend is not forgotten!


I just had that "Ah-Ha" moment reading your comment!
Thanks a lot!!


But I guess this program is applicable only when we have only one more contact to add right?
Say if we needed to add 5 contacts in a shot, this wouldn't work right?
since we cannot assign contacts[contacts.length] to all five I guess?


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