Hi, Can someone explain why total gives number 20 after I run the code?

Tell us what’s happening:
Describe your issue in detail here.

  **Your code so far**

// 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];

}
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/91.0.4472.124 Safari/537.36

Challenge: Iterate Through an Array with a For Loop

Link to the challenge:

total starts out as the number 0, but with the loop you are reassigning it, and written out you are doing:

let total = 0;
total = total + 2
//total = 2 here

total = total + 3
//total = 5 here
 
total = total + 4
//total = 9 here

total = total + 5
//total = 14 here

total = total + 6
//total = 20 here at the end

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