Dawid W.
Dawid W.

Reputation: 13

Adding array elements Javascript

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.

Upvotes: 1

Views: 65

Answers (3)

Abhinav Galodha
Abhinav Galodha

Reputation: 9878

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.

Upvotes: 2

Kamil Latosinski
Kamil Latosinski

Reputation: 846

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);

Upvotes: 0

Damian
Damian

Reputation: 2852

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++) {

Upvotes: 1

Related Questions