I have this algorithm exercise that is very popular with developers that returns:
steps(3)
#
##
###
steps(5)
#
##
###
####
#####
I am studying a version of it developed in a recursive way. The code below is working fine.
function steps(n, row = 0 , stair = '') {
if(n === row) {
return;
}
if(n === stair.length) {
console.log(stair)
return steps(n, row + 1)
}
if (stair.length <= row) {
stair += '#';
} else {
stair += ' '
}
steps(n, row, stair)
}
steps(3)
My only doubt is related to the importance of the 'return' in this part of the code:
if(n === stair.length) {
console.log(stair)
return steps(n, row + 1) // <--- this 'return'
}
If I delete the 'return', like this way:
if(n === stair.length) {
console.log(stair)
steps(n, row + 1) // <-- without the return
}
this generates a looping error on console:
Maximum call stack size exceeded
I want to understand why this happens under the hood. I still don't have much practice with recursive functions.