I created recursive function like so.
function countDown(count){
if(count==0){
return;
}
countDown(count-1)
}
console.log(countDown(5))
The function returns undefined insted of printing numbers from 5 to 1.What i did wrong?
CodePudding user response:
you return nothing, so it's clear it will be undefined.
function countDown(count){
if(count==0){
// you should return a value if you want value instead of undefined
return 100;
}
countDown(count-1)
}
console.log(countDown(5))
CodePudding user response:
Consider your code:
function countDown(count){
if(count==0){
return;
}
countDown(count-1)
}
If your variable named "count" is equal to zero it returns nothing.
Hence, undefined.
If your intention is to print numbers 5 - 1. Change your code like so:
function countDown(count){
if(count==0){
return;
}
console.log(count);
countDown(count-1)
}
countDown(5);
CodePudding user response:
You need ot print inside of the function.
function countDown(count) {
if (!count) return;
console.log(count);
countDown(count - 1);
}
countDown(5);