-1

I wrote simple function that multiplicates until the result becomes one-digit number. For example, when you put 1234 as parameter, the flow would be like this: (parameter: 1234) => (result: 1*2*3*4 = 24) => (parameter: 24) => (result: 2*4 = 8) => return 8.

It produces result that I expected, but it doesn't return value. When I put 1234 as a parameter, it goes through the calculation and the ending result becomes 8, but it doesn't return the result. It's strange because the the console.log works but the return doesn't work.

Why does it work like this?

function multiplicativePersistence (num) {
  if (num >= 10) {
  let result = 1;
    String(num).split('').forEach((ele) => {
      result = result * Number(ele);
    })
    multiplicativePersistence(result);
  } else {
    console.log(num); // 8
    return num; // undefined
  }
}

console.log(multiplicativePersistence(1234)) // console.log says 8 but nothing is returned
2
  • Please don’t put code in comments. Edit the question instead Commented Mar 10, 2020 at 0:50
  • Does this answer your question? Javascript recursive function not returning value? Commented Mar 10, 2020 at 0:56

1 Answer 1

1

You need to return your recursively-called function:

function multiplicativePersistence (num) {
  if (num >= 10) {
  let result = 1;
    String(num).split('').forEach((ele) => {
      result = result * Number(ele);
    })
    return multiplicativePersistence(result); // return here
  } else {
    console.log(num); // 8
    return num; // undefined
  }
}

console.log(multiplicativePersistence(1234))
Sign up to request clarification or add additional context in comments.

1 Comment

OH IT WAS SO...! Thanks for your help

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.