Why this code returns 10 instead of 2?
var arrToSum = [2, 4, 10];
function sumArray(array) {
var result = 0;
for (var i = array[0]; i < array.length; i++) {
result += array[i];
}
return result;
}
sumArray(arrToSum);
// function returns 10
If following loop logic, I would end after adding 2 to result variable, because next i is equal to 3 and loop should end. Please explain what happens there.
iruns from2to2, effectively only addingarr[2](10) to0. It's not clear to me what you are intending withvar i = array[0];. To expand a bit: "because nextiis equal to3" Yes, you are adding only a single value, the loop stops after a single iteration, but sinceistarts at2you are addingarr[2], notarr[0]. Btw, if you want to understand what exactly your code is doing, set a breakpoint, step through your code step by step and inspect the variables.array[2]is 10