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