JavaScript Slice

This method finally clicked in my head today. So basically the way the JS Slice method works is that, it gives you back a copy of the original array. You specify where you want your copy to start. For instance, with slice() you might as well read that as slice the original array starting from position 0. Slice(1) says, I want a slice starting from position 1, while slice(-1) says, I want a slice starting from the last item - in which case you will only get that one item. In such cases where you don't specify the end, the slice method assumes you want a slice till the very last item. If you want to specify the end of your slice, you just pass it to the method, e.g. slice(1, 4), where 4 is the position you want the slice to end at. Now the thing to note is that the item on position 4 will not be in your slice. The slice will actually end on that number you provided minus one. So in this case you would get items starting from position 1 to position 3 of the array. So simply, when specifying the end, you just add one to it.

With this in mind, the following code is a lot easier to understand. One function uses a for loop to iterate over an array, while the other uses recursion and the slice method.

function sum(numbers){
  let total = 0
  for(let i = 0; i < numbers.length; i++){
    total += numbers[i]
 }
  return total;
 }

Recursion:

function sum(numbers){
  if(numbers.length === 1){
    //base case
    // if the array has one item, then thats the total of the array :)
    return numbers[0];
  } else{
    return numbers[0] + sum(numbers.slice(1))
  }
}