title: How can I declare a counter inside of my recursive function? (Additive Persistence: Coderbyte)
body: <p>While working through some Coderbyte challenges, I was able to solve the following problem recursively, but was hoping to get some feedback on how I can improve it.</p>
  
  <blockquote>
    <p>Have the function AdditivePersistence(num) take the num parameter being passed which will always be a positive integer and return its additive persistence which is the number of times you must add the digits in num until you reach a single digit. </p>
    
    <p>For example: if num is 2718 then your program should return 2 because
    2 + 7 + 1 + 8 = 18 and 1 + 8 = 9 and you stop at 9.</p>
  </blockquote>
  
  <p>My submitted, working recursive solution is below. How can I place "count" into my function without letting it get "reset" every time I recurse?</p>
  
  <pre><code>var count = 0;
  function AdditivePersistence(num) {
    count = 0;
    if (num &lt; 10) {
      return count;
    }
    if (num &gt; 10) {
      count++;
      AdditivePersistence('' + num.split("").reduce(function(a,b) {
        return parseInt(a) + parseInt(b)
      }));
    }
  }
  </code></pre>
  
  <p>Here's my broken attempt at moving the counter within the function... would appreciate any pointers for my beginner-self. Beyond just fixing the code, I'd love it if there are other great methods for solving this puzzle!</p>
  
  <pre><code>function AdditivePersistence(num) {
    var count = 0;
    (function recurse(num) {
        if (num &lt; 10) {
        return count;
        }
        if (num &gt; 10) {
          count++;
          recurse('' + num.split("").reduce(function(a,b) {
          return parseInt(a) + parseInt(b);
          }));
        }
      })();
    return count;
  }
  </code></pre>
  
  <p><strong><em>Edit: I just tried with a while loop below</em></strong></p>
  
  <pre><code>function AdditivePersistence(num) {
    var count = 0;
    while (num &gt;= 10) {
      count++
      num = num.toString().split('').reduce(function(a,b) {
        return parseInt(a) + parseInt(b);
      })}
    return count;          
  }
  </code></pre>
  
  <p>Many thanks in advance!</p>