I'm trying to learn recursion, and I found this sample function on the internet. I'm having a hard time following exactly what's happening here. The part that's most confusing to me is, I put a couple of alert commands in the final block (where the arguments are reduced to 2), to see what the values of "first" and "second" are when it gets to this point. The values come up as "4" and "3", and I add these two values right before the return. It comes up as 7. Then the same exact equation is what's actually returned, and it gives the answer "10". Can anyone explain to me how this is working and how it finally arrives at 10?
function sum() {
var args = Array.from(arguments);
var first = args[0];
var second = args[1];
if(args.length === 2) {
alert("first:" + first + " second:" + second );
alert("Sum: " + (first+second) ) //this alerts 7
return first + second; //returned value is 10
}
return first + sum.apply(null, args.slice(1));
}
var results = sum(1,2,3,4);
console.log(results);