I'm trying to learn the concept of recursion, I normally use loops where possible. Can anyone please explain what is happening in this code given the array of numbers.
var set = [1, 2, 3, 4, 5];
function recurs(array) {
if (array.length === 0) {
return 0;
}
else {
return array.shift() + recurs(array);
}
}
console.log(recurs(set));
I understand the if statement it's basically giving the recursion a chance to end. But I'm confused with what exactly is going on in the else statement, I understand the .shift() function removes the first index of the array but then what exactly? I have run through a debugger and still can't quite get my head around it. The correct answer is 15 I just need to fully understand why. If anyone could break it down for me it would be appreciated.