Adding value on an empty array

Adding value on an empty array
0.0 0

#1

I’m trying to add a value to an empty array but it is not showing what I’m expecting.

function sumAll(arr) {
  let tempArray = [];
  if(arr[0] > arr[1]) {
    for(let i = arr[0]; i >= arr[1]; i--) {
      return tempArray.push(i); 
    }
  } else {
      for(let i = arr[0]; i <= arr[1]; i++) {
        return tempArray.push(i);
      }
  }
}

console.log(sumAll([1, 4])); // should return 10.
console.log(sumAll([4, 1]));

The output is

1
1

Where I’m expecting a

[1, 2, 3, 4]
[4, 3, 2, 1]

I hope you could help me.


#2

For the first [1,4] array, the code will skip the first if and run the second for loop in the else. It will set i to 1 then push 1 into temparray. Then it will return temparray immediately. So the for loop never continues.

Same problem for the second test too.

You should not return inside the for loop unless you are really done.
Hope this helps.


#3

Oh , thank you so much.