Be careful of this - while this is recursion, in its strictest sense, it’s also an infinite loop. Fortunately, FCC and codepen (and other mature online dev environments) catch and short-circuit that, but it’s “infinite nested Russian dolls.”
In order for recursion to be useful, there has to be an end-point. Just as in a for loop or a do-while or whatever mechanism, there needs to be a defined end point.
Is recursion more efficient? In general, not so much. It can be more legible and logical, under certain circumstances, but it all depends on personal preference (or, more accurately, assuming you are working towards a career, your employer’s preference).
In terms of efficiency, if that is a good benchmark, simple iterative loops are faster than higher-order functions ( like
.forEach), which are faster than recursion. In general. Individual mileage may vary.
In terms of what it actually does, the key to recursion working well is two things: an end point, and a return value. As the recursive loop gets deeper and deeper, a series of returned values are being stacked, from each recursive step. When that end point is reached, the entire stack of return values is collapsed, by whatever mechanism you specify.
There are ways to simply have the recursive values added, or to have an array or a string built by a recursion, or all sorts of creative ways. What you do with the value being returned from that recursion will determine the final return from the outermost, original, call.
Yeah, recursion is confusing as hell. Every time I think I’ve got a handle on it, I realize it’s slipped on me again. It takes time, and practice, to see any practical use for it. But there are use cases, there are times when it’s the right tool for the job.