I'm a pretty experienced frontend engineer with a weak CS background. I'm trying to get my head around the concept of recursion. Most of the examples and purported explanations I can find just aren't explaining it in a way I find easy to understand.
I set myself a task of writing a function that will reverse a string recursively. I know there has to be a base condition (i.e. the solution is found), but I can't figure out how to actually write something like this and could use a demo to study.
Could someone provide a sample function?
According to the MDN Web Docs, you should use
substring()
instead ofsubstr()
:Additionally, if no index is provided as a parameter to
charAt()
, the default is0
.Therefore, we can write a recursive one-liner to reverse a string using a ternary operator and by applying the logic described above:
Something like:
So the function is recursive as it calls itself to do the work.
A tail recursive version, just for kicks (even though JavaScript doesn't perform tail call elimination):
The base case that I am using for exiting the recursion is when the the length decrease to 0
On each recursive call we will take out the last character of the string and append it with the result that we will get from recursive call of a string, which is smaller in size as the last character is removed using slice.
//call this function with the string as parameter