A "recursive" function is a function that calls itself until you tell it to stop. Here's a quick example:
Oreo Cookie Tower recipe :
You will need:
1 Oreo cookie tower (optional)
1 Oreo cookie
Directions:
- If you have an Oreo cookie tower, remove the top chocolate cookie wafer from it and eat it
- If you have an Oreo cookie tower, remove the top chocolate cookie wafer from the Oreo cookie and eat it
- If you have an Oreo cookie tower, place the exposed cream surface from the Oreo cookie tower against the exposed cream surface of the Oreo cookie
The whole idea is you can repeat that recipe as many times as you wanted and your cookie tower would get as big as you wanted it to be.
In that example, the word "optional" turns the Oreo Cookie Tower ingredient into another phrase you may have seen. If you ever see the term "escape condition", that's what it's referring to.
The best way to do this recursively would be with a helper function. Like this
function sumDigitsHelper(result){
// check to see if result is empty here. If it is, return 0.
// grab the first number from result here and store it in a variable called "first"
// grab the rest of the array here and store it in a variable called "rest"
// return first + sumDigitsHelper(rest)
}
function sumDigits(number){
var number = Math.floor(Math.random() * 100) + 1;
var result = number.toString().split("");
// I'll leave this commented so you can remember what it does
// var last = eval(result.join('+'));
return sumDigitsHelper(number);
}
Just replace my comments with code.