I try to add a numbers from 1 to 10 by JavaScript using the concept of recursion and it didn't work as intended. it revers the operation and it come up with the first result and when i use variable to store the result i get it come up with undefined. here is the code
var total = 0, count = 1;
function sum(total, count){
if(count <= 3){
total =count;
count ;
sum(total, count);
}else{
return total;
};
}
var result = sum(total, count);
console.log(result);
CodePudding user response:
You are not returning from your first if
condition. Default return value for any function is undefined
.
var total = 0, count = 1;
function sum(total, count){
if(count <= 3){
total =count;
count ;
return sum(total, count);
}else{
return total;
};
}
var result = sum(total, count);
console.log(result);