# Basic JavaScript - Iterate Through an Array with a For Loop

Tell us what’s happening:
Describe your issue in detail here.
I’m trying to solve this, but it didn’t return 20. what shall I do?

``````// Setup
const myArr = [2, 3, 4, 5, 6];

// Only change code below this line
for (let total = 0; total < myArr.length; total++) {
myArr[0] + myArr[1] + myArr[2] + myArr[3] + myArr[4];
}
``````
``````**Your browser information:**
``````

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

Challenge: Basic JavaScript - Iterate Through an Array with a For Loop

I slightly modified your code and tested it:

``````const myArr = [2, 3, 4, 5, 6];

// Only change code below this line
for (let total = 0; total < myArr.length; total++) {
myArr[0] + myArr[1] + myArr[2] + myArr[3] + myArr[4];
console.log(total) //I added this line to see what's going on on the each loop step
}

//Output:
/*
0
1
2
3
4
*/
``````

You need to accumulate result in the total variable, but obviously it is not happening.
Maybe we don’t need total here in the line below?

``````for (let total = 0; total < myArr.length; total++)
``````

The instruction says initialize total as 0

You don’t initialized the total in the loop head. Look at the example. You initialize the index variable in the loop head.

Line inside the loop also is not right. What do you think this line is doing?

1 Like

It adds items in the array

No.

the line above is the sum of 5 elements of myArr

I am not sure you need to use such line of code inside the loop.

Also, even if you’re getting this sum… You didn’t assigned it to any variable, or I could say, you didn’t use it in your code at all

I’ve figured out that instead of using myArr[0] + myArr[1] + myArr[2] + myArr[3] + myArr[4]; i can use total = 0;
total += myArr [i];

Yeah, that looks good. So you passed the tests? If no, post your new code and feel free to ask questions if you have any.

yeah, I passed the test,10x a lot, I appreciate it

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