0

I am trying to add all array elements with basic for loop for some reason, my variable 'result' return NaN.

let array = [1, 2, 3, 4, 5];
let result = 0;
const arraySum = (arr) => {
  for (let i = 0; i <= arr.length; i++) {
    result = arr[i] + result
  }
  console.log(result)
}
arraySum(array)

Please use basic looping to answer, I tried .reduce method but want to use basic loops Thank you

1
  • @TalmacelMarianSilviu If you're going to give an answer, post it in the Answer section, not a comment. Commented Jun 30, 2020 at 23:07

6 Answers 6

3

Your condition of i <= arr.length should be using i < arr.length

The length of the array is 5 but the index of the last number is 4, so you don't want <= there.

let array = [1, 2, 3, 4, 5];
let result = 0;
const arraySum = (arr) => {
  for (let i = 0; i < arr.length; i++) {
    result = arr[i] + result
  }
  console.log(result)
}
arraySum(array)

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

Comments

2

Length start at 1, so you need to set < operator in your loop :

let array = [1, 2, 3, 4, 5];
let result = 0;
const arraySum = (arr) => {
  for (let i = 0; i < arr.length; i++) {
    result = arr[i] + result
    console.log(result)
  }
  console.log("result = ", result)
}
arraySum(array)

Comments

1

The reason for this problem is that the array has a length of 5 and the last index is 4. When the loop is at index = 5 there is no element at position 5. The result will therefore be undefined. To avoid this problem, the for loop should be like this:

for (let i = 0; i < arr.length; i++) 

or

for(const i in arr) 

Comments

0

You put '<=' in the for loop but you must use just '<'. if array = [1,2,3] then length = 3 but array index goes from 0 to 2 not 3

Comments

0

you could try, if simple enough:

let array = [1, 2, 3, 4, 5];
let result = 0;
arraySum = (arr) => {
  for (let i = 0; i < arr.length; i++) {
    result += arr[i]
  }
  console.log(result)
}
arraySum(array)

Comments

0

the "<=" shoud be placed by "<"

let array = [1, 2, 3, 4, 5];
let result = 0;
const arraySum = (arr) => {
  for (let i = 0; i <= array.length; i++) {
    result += array[i];
  }
  console.log(result);
};

arraySum(array);

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.