First, I perfectly understand what’s happening with this piece of code here:
var myArray = ;
// Only change code below this line.
for (var i = 1; i <= 5; i++) {
myArray.push(i);
}
It’s adding 1 (i++) to the numbers below 5 and it stops when 5 is reached, so we have 1, 2, 3, 4, 5.
But I can’t understand the following code:
var myArr = [ 2, 3, 4, 5, 6];
// Only change code below this line
var total = 0;
for (var i = 0; i < myArr.length; i++) {
total += myArr[i];
}
What is driving me crazy is the fact I can’t see how it could be useful in a real project, for what reason I’d use this, and why we’re using i++ in this case. I passed the test but I need to understand what’s going on.
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];
// Only change code below this line
var total = 0;
for (var i = 0; i < myArr.length; i++) {
total += myArr[i];
}
Your browser information:
Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0
.
Link to the challenge:
https://www.freecodecamp.org/challenges/iterate-through-an-array-with-a-for-loop