This function has to return reversed string. For example, “dog” -> “god”.
It works correctly but I don’t understand the logic and I need explanation
function reverse (str) {
if (str.length <= 1) return str;
return reverse(str.slice(1)) + str[0]
}
>Solution :
Explaination
Firstly, you call reverse(“dog”) and it return reverse(“og”)+”d”
Then the reverse(“og”) continue to run again. It returns reverse(“g”)+”o”
The last one, reverse(“g”) only returns “g” since the if statement is true
Then you plug the reverse(“g”) to the reverse(“g”)+”o”, as a result “go” is returned
Finally, plug reverse(“og”) to reverse(“og”)+”d”, which is “go”+”d”, as a result “god” is the output
The flow
- (1) reverse("dog") called -> return reverse("og")+"d"
- (2) reverse("og") called -> return reverse("g")+"o"
- (3) reverse("g") called -> return "g" (if statement)
- (4) plug (3) to (2) -> return "g" + "o" -> "go"
- (5) plug (4) to (1) -> return "go" + "d" -> "god"