+ 1

Can't understant the array[index]

Why does this code print 20 and not 18 ? var myArr = [ 2, 3, 4, 5, 6]; var total = 0; for (var i = 0; i < myArr.length; i++) { total += myArr[i]; } console.log(total); //Prints 20, why ? /*Won't i become equal to 1, and the 1 index is "3" because javaScript arrays start counting from 0 */

18th Jul 2020, 9:17 PM
Marina Khamis
Marina Khamis  - avatar
1 Respuesta
+ 4
The loop goes over the indexes 0 to 4 and adds every item to total. 2+3+4+5+6 == 20.
18th Jul 2020, 9:28 PM
HonFu
HonFu - avatar