Algo Scripting: Sum of All Numbers in a Range

Hello campers!
I just have a quick question about my code. I solved this exercise with my own code without looking up hints (this is a first and i’m very proud ATM sorry for bragging lol), but after I passed the exercise I wanted to compare my code with other solutions and none of them approached it like I did… So here’s my question: Was my approach decent code? I realize my own answer is a few lines longer but would my code have been something that would have been used in a workplace situation?
Sorry if this seems like a dumb question. I’m just curious of where my skill level is relatively speaking.

function sumAll(arr) {
  let count = [];
  if (arr[0] > arr[1]) {
    arr = [arr[1], arr[0]]
  }

  for (let n = arr[0]; n <= arr[1]; n++) {
    count.push(n)
  }
  return count.reduce((num1, num2) => num1 + num2);
}

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

HI!

So your code looks completely correct in that it does what it is meant to do, but nobody really does it this way for performance reasons - imagine, what would happen if someone wanted sumAll(1, 1000000000) (a bit of an extreme example) - in that case, you would be creating an array with 1 BILION items in it, and if we just for simplicity assume each of those numbers is four bytes, you have just created an array that takes ~4 GB of PC RAM (because the array needs to be stored somewhere). Also, keep in mind that creating such an array probably took you some time, say, 5 seconds. And then you need to go through the array all once again to reduce it to the sum, which takes up 5+ seconds AGAIN.
Realistically though, no one is going to call anything more extreme than sumAll(1, 1000000), but still, it is 4 MB of RAM and 6 ms that could have been saved.

Thank you for your feedback!
So in short, it would be best to learn to use methods to achieve the same result as my loops and statements?

Not really. Although that is often helpful, that really comes only from experience. What I was trying to say is that you are creating an array although you don’t need to, and that can very easily get very slow. My idiomatic solution for this problem would be something along the lines of

function sumAll(arr) {
  let sum = 0;
  if (arr[0] > arr[1]) {
    arr = [arr[1], arr[0]]
  }

  for (let n = arr[0]; n <= arr[1]; n++) {
    sum += n;
  }
  return sum;
}

I’m not sure about the way to learn this. As in most things, the best way is only really just practice, practice, practice.

Oh wow. That looks so much better!
I’ll keep at it. Thank you again.