Odd Thing Happening With My Code

This was my solution (overkill, I know) to a CodeWars challenge. I added a console.log() when testing and noticed it logs multiple times. If I wrap it in an else, it only runs once, as I expected. Just wondering what’s going on there. Thanks!

function persistence(num) {
  let count = 0;
  testNum(num);

  function testNum(num) {
    if (num > 9) {
      count += 1;
      multiply(Array.from(num.toString()));
    } 
    console.log(count)
    return count;
  }
  
  function multiply(arr) {
    let tot = 1;
    for (let i = 0; i < arr.length; i++) {
       tot *= arr[i];
      }
        testNum(tot);
    }
  return count;
}

Trace your function call execution - testNum and multiply call each other so you’ll get multiple console logs.

I ran it through the debugger and see what’s happening, but don’t fully get why it’s happening. I believe it’s just returning to where it was called from, which makes sense, but I still don’t get why it returns to the last line, and why it keeps going back and forth before finally reaching the final return statement. And I still don’t get why it runs the console.log multiple times when not using else. I guess it doesn’t really matter, but it seems inefficient, and I’m just curious.

I realized I didn’t actually need a return statement in testNum(), so I removed it, but it still jumps back and forth to each function before finally returning. I guess that’s just how JS works, even without an explicit return. I tried adding a break; where I removed return count; but it gives me an ‘Illegal break statement’ error. Do you know if there’s a way to get it to just go straight to the final return statement? Thanks

If you don’t want to go back an forth between the two functions, don’t call the functions in each other.

It wasn’t that I didn’t want them to go back and forth, but that I didn’t want them to go back and forth after the fact, when it wasn’t necessary. Anyway, I refactored it without the functions:

    function persistence(num) {
      let count = 0;
      let arr = Array.from(num.toString());

      while (arr.length > 1) {
        count++;
        arr = arr.reduce((tot, cur) => {
          return tot *= cur;
        });
        arr = Array.from(arr.toString());
      } 
      return count;
    }

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.