I’m trying to print a string from number n through 1 using this recursive function:
function numStr(n) {
let outputStr = '';
if (n === 1) {
return outputStr + n;
} else {
outputStr + n;
return numStr(n-1);
}
}
console.log(numStr(5)); //should print 54321I know changing the lines 7 and 8 to return outputStr + n + numStr(n-1) does the job. But I can’t figure out why the above code doesn’t work as expected. It prints ‘1’ in all cases.
Advertisement
Answer
When n!=1 then you are just appending the n to a variable ouputStr but you are not actually returning this outputStr value. Change the code to:
function numStr(n) {
if (n === 1) {
return '1';
} else {
return n+numStr(n-1);
}
}
console.log(numStr(5)); //should print 54321