Search code examples
javascriptfor-loopstring-lengthvariable-length

How do I read this "for-loop" code from freecodecamp


this is basically the code, I already got the right answer but I'm just trying to figure out how the process work

total = 20

   var myArr = [ 2,3,4,5,6];
    var total = 0;

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

    }

and I did this

   var myArr = [ 2,3,4,5,6];
var total = "";

for (var d = 0; d < myArr.length; d++){
   total += myArr;

}

the output is.... (total is =""; so I can see what's happening inside but..

total= 2,3,4,5,62,3,4,5,62,3,4,5,6

and got confuse then I change the myArr to d

var myArr = [ 2,3,4,5,6];
var total = 0;

for (var d = 0; d < myArr.length; d++){
   total += d;

}

why is it

total = 10?


Solution

  • I've added comments to your working solution as below.

    //Create new array to store our range
    var myArr = [ 2,3,4,5,6];
    //create new variable to store our total at the end
    var total = 0;
    
    //repeat code within when d < the length (or number of values) in our array, increment d each time it runs
    for (var d = 0; d < myArr.length; d++){
       //take the current total and add the current value in our array to it each time
       // first time it will be 0 (total) + 2 (myArr[0]) second time it will be 2 (total) + 3 (myArr[1]) and so on.
       total += myArr[d];
    
    }
    

    As another user has pointed out in your second attempt you've changed the datatype of total from a number to a string.