1

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.

2
  • 2
    Because i runs from 2 to 2, effectively only adding arr[2] (10) to 0. It's not clear to me what you are intending with var i = array[0];. To expand a bit: "because next i is equal to 3" Yes, you are adding only a single value, the loop stops after a single iteration, but since i starts at 2 you are adding arr[2], not arr[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. Commented Dec 28, 2016 at 20:47
  • 2
    Because array[2] is 10 Commented Dec 28, 2016 at 20:48

3 Answers 3

2

How things are working in for loop:

for (var i = array[0]; i < array.length; i++) {

In the loop, these are the results after execution of first Iteration;

First Iteration; i = 2

var i = array[0]; // i = 2;
result += array[i]; // result = 10;

array[i] is array[2] which is 10. Hence, the result is 10.

Second Iteration; i = 3

array.length is 3 since it has 3 elements. Condition i < array.length; is false and code Breaks out of loop, returning the Result as 10.

Sign up to request clarification or add additional context in comments.

Comments

1

You are starting from 2 (value of array[0]), not from 0. Change

for (var i = array[0]; i < array.length; i++) {

to

for (var i = 0; i < array.length; i++) {

Comments

0

This is why you should familiarize yourself with functional programming in javascript. map, filter, reduce are your friends. Especially map.

Try to avoid regular loops as much as possible cause they are more error prone. In your case you've messed up with counter variable i.

var sum = [2, 4, 10].reduce((a, b) => a + b, 0);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.