sanket sanket - 3 months ago 8
Javascript Question

getting error on recursion in JavaScript.



var summation = function (num) {
if(num <=0){
console.log("number should be greater than 0");
}else{
return(num + summation(num-1));
}
};
console.log(summation(5));





it gives me NaN error but i want summation of number.where am i making mistake?

Answer

In your last iteration, you correctly check whether the input is <= 0, but then return nothing, which results in an implicit return value of undefined.

Adding undefined to a number results in NaN:

console.log(1 + undefined); // NaN

To resolve this, return 0 if your cancellation condition has been hit:

var summation = function(num) {
  if (num <= 0) {
    console.log("number should be greater than 0");
    return 0;
  } else {
    return (num + summation(num - 1));
  }
};
console.log(summation(5));