Iterate Through an Array with a For Loop how did we get "20"

Tell us what’s happening:

i didn’t unserstand this very well… can any one explain to me how did we get 20 in more simple way if it’s possible

Your code so far


// Example
var ourArr = [ 9, 10, 11, 12];
var ourTotal = 0;

for (var i = 0; i < ourArr.length; i++) {
ourTotal += ourArr[i];
}

// Setup
var myArr = [ 2, 3, 4, 5, 6];
var total=0;
for(var i=0 ;i < myArr.length;i++)
{total+=myArr[i];}
// Only change code below this line
console.log(total)

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36.

Challenge: Iterate Through an Array with a For Loop

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/iterate-through-an-array-with-a-for-loop

2+3+4+5+6 = 20

The value 20 comes from the sum of the numbers inside the array

1 Like

@ilenia and how we get that value to the variable “total” ?

See if you can explain to us what you think the following code does?

for(var i=0 ;i < myArr.length;i++)
{total+=myArr[i];}

@RandellDawson i think it set the total of myArr values as a value for total or something like that

but what steps does that code?

@ilenia i have no idea :sweat_smile:

do you know what a loop does?
do you know what += does?

total+=myArr[i]; means total = total +myArr[i];
the only thing i don’t get in this code is i<myArr.length

i < myArr.length is the condition that breaks you free from the loop. In your case, myArr.length is 5. After 5 iterations of the loop it will exit, having added all 5 of the items from your array to total.

1 Like

oh yeah!! finally i get it thank you so much all you helped a lot