Why does this fail: Sum All Numbers in a Range

Tell us what’s happening:

So my code continues to fail and I don’t know why?
My suspecion is on line 7 but i am not sure

Your code so far


function sumAll(arr) {
let myMin = Math.min(arr); //gets the lowest number of the array
let myMax = Math.max(arr);
//get's the highest number of the array

while (myMin < myMax) { //while the biggest number is bigger then the smallest one
return myMin.push(arr);
//return the smallest number and pushes the numbers through

}
}

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/86.0.4240.193 Safari/537.36.

Challenge: Sum All Numbers in a Range

Link to the challenge:

consider the below code:

function arith(a, b){
    let sum = a+b;
    let mul = a*b;
    return sum;
    return mul;
}

In the above code, we’re returning variable sum first, then variable mul
But interesting thing is, as you’re returning the sum, javascript doesn’t evaluate rest of the code in function;

In your case you have used return inside the loop, as soon as you return, javascript will not even evaluate next iteration of the loop, it’ll just stop execution of the function
Hope this helps;

2 Likes

It’s a good catch - the return isn’t doing what you might think. If you look up Array.push(…) on MDN, and look for the section “Returns:” That tells you what the function actually sends back to your code.

In this case, push(…) returns the new length of the array.

1 Like
// Try  this method using by spread operator and reduce method.

function sumAll(arr) {
   const minVal = Math.min(...arr)
   const maxVal = Math.max(...arr)
   let list = [] 
   for(let i = minVal; i <= maxVal; i++){
      list.push(i)
   }
   return list.reduce((prev, next) => prev + next);
}
console.log(sumAll([1, 4]))

Please do not resurect old topics to post solutions.


It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

I added [spoiler] and [/spoiler] tags on the line above and below your solution code.