0

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?

1
  • @blex thanks, it works :) Commented Aug 23, 2016 at 14:09

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

thanks it's working now and i also got my mistake :)
0

Try

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

Comments

0

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

there was no terminate statement for recursion earlier

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.