Function Recursion
Another technique of functional programming involves functions calling themselves recursively. This generally means you start with a big problem and break it down into multiple instances of the same problem, but in smaller chunks each time the function is called.
One common example of recursion is a function to reverse the characters of a string, reverse(str)
. Think about how you can state this problem in terms of itself. Let's say you have a string, "abcd"
, and want to reverse it to "dcba"
. Recognize that "dcba"
can be restated as follows:
reverse("bcd") + "a"
In other words, you are taking the input string and breaking it down into a smaller problem by taking off the first character and making a recursive call with the remaining characters of the string. This may be easier to see in the following code:
function reverse(str) { Â Â Â Â if (str.length == 1) return str; Â ...