Solution Review: Length of a String
This review provides a detailed analysis of the solution to find the length of a string recursively.
We'll cover the following...
Solution: Using Recursion
Press + to interact
function recursiveLength(testVariable) {// Base caseif (testVariable === "") {return 0;}// Recursive caseelse {return 1 + recursiveLength(testVariable.substr(1));}}// Driver CodetestVariable = "Educative";console.log(recursiveLength(testVariable));
Explanation
In Javascript it is preferable to use
.length
function for finding the length of a string. However, this exercise is meant as practice. Here we teach how to find the length of a string recursively. Also, this concept can be used on various other problems that involve counting something in a string.
The base case for this solution (line number 3 to 5) will test for an empty string ""
. If the string is empty we return .
For the recursive case, (line number 9), we call another instance of the same function, but we remove the first element. When the child element returns the length, we add to ...