Help with understanding a Javascript for loop

Hi all, I’m going through this book called “Head First HTML5 Programming” and it is teaching a lot of javascript in the first few chapters in order to understand the javascript APIs you can use with HTML5. The book doesn’t seem to have it’s own forum so thought I’d just post my question here if that’s ok. Here’s the code I’m having a hard time understanding:

function addUp(numArray) {
     var total = 0;
     for (var i = 0; i < numArray.length; i++) {
          total += numArray[i];
     }
     return total;
}

var theTotal = addUp([1, 5, 3, 9]);

So then the question in the exercise is what is the value of theTotal? I couldn’t figure out what it was so I looked up the answer and found it to be 18. So I see that the numArray was added up right? 1 + 5 + 3 + 9 = 18
But I’d like to understand why? I understand up to the point of the line that says:

total += numArray[i];

That’s what’s throwing me off. So if I understand right…the for loop will loop as long as it’s less than 4 because numArray.length is the amount of the items in the array which is 4 right incrementing by 1 each time from 0 up? But I don’t understand that total line.

I’m really not that great with Javascript (in fact, I’m actually pretty bad/basic), but I think I know what it does. (Confident in this post, yet? (: )

Right.

I’ll just break down the entire line of code.

So first the author is defining the function ‘addUp’. A practical name, to be sure. I hope you understand what I mean when I say that the ‘input’ for the function is the variable numArray (which seems to be an array that he/she’s already defined.

In the function, the author wants the following to occur:

  1. The browser to define the variable total for a value of 0.

  2. To run the for loop such that:
    a. variable i is defined for 0 (the first number in the array - tricky, isn’t it?)
    b. that it continue while i is less than the length of the numArray array (which, in this case, is 4).
    c. if it is less, then the browser should add 1 to i after it’s done.

  3. Every time the for loop runs, the following should happen:
    a. the variable total (right now, it’s 0) should be added to the current value in the array. If you want to think of it in a different way, think of it as, “Add the value of the array ‘numArray’ to the existing total”.

  4. Finally, after the for loop completes, the function addUp will return the variable ‘total’

The author then defines the Total as the returned value (the variable ‘total’) of the function addUp for values 1, 5, 3, and 9 of the array numArray.

Hope I helped.
~TehYoyo

Doesn’t your book list JavaScript operators? https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Expressions_and_Operators#Assignment_operators

Thank TehYoyo for answering. This is somewhat helpful but I still don’t see what the loop has to do with 1 + 5 + 3 + 9 = 18. If all we’re doing is adding the numArray up then what’s the point of the loop? I just don’t know why I can’t get this. These loop things just confuse me.

Thanks for the link.

The purpose of the loops is to keep adding numbers until you finish all of your addition. Keep in mind that, as it’s a textbook, it might not use the most efficient way of doing things, it might use things just to show how it’s done.

A better example of where a for loop would be necessary is if you’re using a timer to display instructions (like a contest - option1, ‘the contest is still going!’, option 2 - ‘sorry! the contest is over!’, but even then you could use an if…else statement.

~TehYoyo

Ok…would it be possible to show me what the math is doing each time the loop runs through? Maybe that would help me see it better. I’ve understood other loops that were shown but I’m not sure why I just do see what’s happening here.

You can add a console.log to view what is going on in your browser/Firebug’s debugger:

total += numArray[i];
console.log(total);

Ok this is cool. I can break down the code to see what I get. I’ve been trying this but I’m not quite sure how to see what total is though. If all I type is those 2 lines above then I get total is not defined. So then I typed out the whole function and everything that I have up top at the beginning of this thread but then after typing in console.log(total) I get Reference Error: total not defined. So is that because total is only a local variable within the function addUp? I’ve tried several different things but I can’t quite seem to get it to report what total is doing. I also tried not closing the function to get total but then of course I get a Syntax error because I’m missing the ending curly brace. So how do I get it to show me what total is doing?

Here is the function that we are using:


function addUp(numArray) {
     var total = 0;
     for (var i = 0; i < numArray.length; i++) {
          total += numArray[i];
     }
     return total;
}

When the function is called with an array of [1, 5, 3, 9], the addUp function will be passed that array in the variable called numArray and the array will contain four values.
numArray[0] will be 1
numArray[1] will be 5
numArray[2] will be 3
numArray[3] will be 9

It is possible to not use a for loop, and to just return a total with:


return numArray[0] + numArray[1] + numArray[2] + numArray[3];

but doing that restricts it to being able to work only with arrays that have at least four items.
This is why we use the length of the array as a part of the loop, so that we can go from 0 up to the last item of the array.

Here’s how it works with the addUp function.

The for statement is made up of three parts: initial, condition, and the final expression.

[list][]The initial part is executed only once, before any of the looping in the for loop occurs.
[
]The condition is checked before each loop, to check if the code inside of the for loop should be executed.
[*]The final expression is done at the end of each loop.[/list]

When the interpreter gets to the for statement, this is the value of the variables:

total: 0
i: undefined

The for loop runs the initial expression (var i = 0), which sets i to 0;

total: 0
i: 0

The for loop then checks if the condition is still true.
i < numArray.length

i is 0, and numArray.length is 4. 0 is less than 4, so the condition is true and the code in the for loop is executed.

total += numArray[i];

i equals 0, and the value at numArray[0] is 1, so 1 is added on to the total.
After executing the above line the total will be 0 + 1 which ends up being 1.

At the end of the for loop, the final expression is executed (i++), which increases the i value from 0 to 1

Now at the end of the loop, these are the values that we now have:

total: 1
i: 1

The for loop then checks if the condition is still true.
i < numArray.length

i is now 1, and numArray.length is 4. 1 is less than 4, so the condition is true and the code in the for loop is executed.

total += numArray[i];

i equals 1, and the value at numArray[1] is 5, so 5 is added on to the total.
After executing the above line the total will be 1 + 5 which ends up being 6.

At the end of the for loop, the final expression is executed (i++), which increases the i value from 1 to 2

Now at the end of the loop, these are the values that we now have:

total: 6
i: 2

The for loop then checks if the condition is still true.
i < numArray.length

i is 2, and numArray.length is 4. 2 is less than 4, so the condition is true and the code in the for loop is executed.

total += numArray[i];

i equals 2, and the value at numArray[2] is 3, so 3 is added on to the total.
After executing the above line the total will be 6 + 3 which ends up being 9.

At the end of the for loop, the final expression is executed (i++), which increases the i value from 2 to 3

Now at the end of the loop, these are the values that we now have:

total: 9
i: 3

The for loop then checks if the condition is still true.
i < numArray.length

i is 3, and numArray.length is 4. 3 is less than 4, so the condition is true and the code in the for loop is executed.

total += numArray[i];

i equals 3, and the value at numArray[3] is 9, so 9 is added on to the total.
After executing the above line the total will be 9 + 9 which ends up being 18.

At the end of the for loop, the final expression is executed (i++), which increases the i value from 3 to 4

Now at the end of the loop, these are the values that we now have:

total: 18
i: 4

The for loop then checks if the condition is still true.
i < numArray.length

i is 4, and numArray.length is 4. 4 is not less than 4, so the condition is false.

The for loop is now finished, and execution carries on from the statement that comes after the for loop.

In this case, that is to return the value in the total variable, which is 18.

THANK YOU Paul Wilkins!!! That’s it. That right there is what I was missing. I just didn’t realize that the numArray[i] was referring to the indexes of the array. So now I understand it. I understood how the looping worked but I just couldn’t get how that math was working because the numbers of the indexes in the array were throwing me off. Thank you so much for explaining all that in detail but that right there is what helped me get it. Finally. I’m so glad I posted my question in the forums. I figured well I may look dumb for asking my question but if I want to understand this I just better ask my dumb question. :wink: Thanks so much. I’m sure I’ll have more questions coming though as I keep on trying to learn this. I’m not gonna give up this time.

Paul Wilkins broke it down perfectly for you. To answer your question, no, you needed to have added the console.log to the code you posted above like so:


function addUp(numArray) {
     var total = 0;
     for (var i = 0; i < numArray.length; i++) {
          total += numArray[i];
          console.log(total); // Added this line
     }
     return total;
}

var theTotal = addUp([1, 5, 3, 9]);

Then using Chrome’s Javascript Console (Wrench ->Tools ->Javascript Console) or Firebug for Firefox, you can see the change in the total variable every time the loop runs:

Yes Paul Wilkins did break it down perfectly for me. I’m gonna read through his post again to make sure I’ve got it. But that’s exactly what I needed to help me understand what was going on here. Thanks for showing me where to put console.log also. I’m gonna check that out. Thanks so much. I definitely know where to come to ask questions.