0

So I have this recursive function which takes in two parameters, factor and width. The factor will decrement in every recursive instance by 0.05. And in every instance it will be multiplied with width to get a value.

If this value is greater than 900 then the recursive function will continue. If it is less than 900 then it will stop and return the factor value.

Right now I'm getting undefined but if I log all the factors then I can see that there are numbers before undefined but it stops with undefined.

How can I get the factor value which is just before undefined?

Here's the snippet:

function findFactor(factor, width) {

  let nextFactor = factor - 0.05;
  let value = width * nextFactor;

  console.log(nextFactor);

  if (value < 900) {
    return nextFactor;
  } else {
    findFactor(nextFactor, width);
  }

}

console.log(findFactor(1, 2400));

8
  • Is this for homework? Commented Oct 14, 2021 at 14:45
  • Ummm yeahhhh :'( Commented Oct 14, 2021 at 14:47
  • 2
    Does this answer your question? undefined returned from function Commented Oct 14, 2021 at 14:48
  • 1
    Depends on your search strategy. I searched for "[javascript] return recursive undefined" and found quite a few answers. In my case, it was complicated by having to sort by age rather than relevance (as I was looking for the oldest question to link as an original). Commented Oct 14, 2021 at 14:54
  • 1
    ... There were irrelevant questions as well, but a large part of that is the number of low-quality and repeated questions on SO these days. Commented Oct 14, 2021 at 14:55

1 Answer 1

2

You are properly returning the result in case if (value < 900) {. However, you forgot to return the result of the subsequent recursive call. Adding return should solve your problem:

else {
  return findFactor(nextFactor, width);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Answers shouldn't merely be code-drops, but should include explanations.
Thank you, will add a small explanation

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.