Intermediate Algorithm Scripting - Sum All Numbers in a Range

Why does this come back in the console as NaN?

Your code so far

function sumAll(arr) {
 arr.sort()
for(var i=arr[0];i<arr[1];i++);
 let sum=0
sum+=arr[i]
return sum
}

console.log(sumAll([1,4]));






Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36

Challenge: Intermediate Algorithm Scripting - Sum All Numbers in a Range

Link to the challenge:

This sort won’t do what you want

You are redefining sum on every loop iteration

Don’t use var

Is i an index for the array arr?

You are returning inside of your loop, so it will only iterate once

is i not an index for the arry arr?

Well, what is inside of arr?

It depends but its always two numbers

Ok, and i starts at one of those two numbers, right?

What does i start at for arr = [5, 8]?

well I hoped it would start with the first index in the array, which would be five

Right, you want i to start at 5 (spoiler, your sort isn’t going to always work right).

What is arr[5] if arr = [5, 8]?

Well I’d think that there is no arr[5], because there is only two values in the array, not 6

Exactly. So you probably don’t want to add arr[i]

Oh of course! So then how do you get i to start at index 0?

i is starting at the value stored in arr[0] already

right so just i=0 then to start the loop I guess

Hold up. What do you want this loop to do? Why would you want it to start at 0?

How do I get it so it starts at index zero of the array

So again I ask, what do you want the loop to do.

Currently, the loop index variable i, starts an the first number in arr and stops an the second number in arr. What do you want the loop itself to do?

This isn’t about finding the “right syntax”. Its about having a clear plan for what the code should do and then writing syntax that matches the plan.

Here’s what I have now

function sumAll(arr) {
  arr.sort()
  let arr2=[]
  for (let i=arr[0]+1;i<arr[1];i++)
arr2.push(i);
let sum=0
for (let j=0;j<arr.length;j++)
sum+=arr2[j]
  return arr[0]+arr[1]+sum

}

console.log(sumAll([1, 4]));

Please hold up.

Please use human words to describe what you want the loop to do.

It’s so much easier to help if we share the same plan for what the code needs to do.

The first loop I would like to go through each number in between the two elements of arr, and then push them into an array. This is so I can find the sum of all the numbers in between the elements

Cool. You don’t need to make a second array, but that gives us a place to start.

Please put {} around your loop bodies.

Why are you starting at arr[0] +1 here?