sanket sanket - 1 year ago 87
Javascript Question

getting error on recursion in JavaScript.

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

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

Answer Source

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));

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download