title: JavaScript function randomly returns undefined when inside If statement
body: <p>I'm learning JavaScript and have this very simple app that returns a random item from an array, but only if it's different to the previous item returned. My code is below. It works fine generally, but randomly returns undefined sometimes even when the <code>console.log</code> on the previous line returns a valid item. If I have the return outside of the If statement it never returns undefined.</p>
  
  <p>Why does my function only sometimes return undefined when inside the If statement and work fine outside?</p>
  
  <pre><code>let ranArray = [
      "flaky","pickle","grass","juicy","desert","wonderful","even","signal","frail","team","addition"
      ];
  
  let previousRanNum = 12;
  
  function generateNumber (){
      return Math.floor(Math.random()*11);
  };
  
  function getItem(){
  
      let ranNum = generateNumber();
  
      if (ranNum !== previousRanNum) {
          previousRanNum = ranNum;
          console.log(ranNum);
          console.log(ranArray[ranNum]);
          return ranArray[ranNum];
      } else {
          getItem();
      }
  };
  </code></pre>
  
  <p>debug console:</p>
  
  <pre><code>getItem()
  undefined
  10
  addition
  </code></pre>
  
  <p>The following works fine and never return undefined:</p>
  
  <pre><code>function getItem(){
  
      let ranNum = generateNumber();
  
      if (ranNum !== previousRanNum) {
          previousRanNum = ranNum;
          console.log(ranNum);
          console.log(ranArray[ranNum]);
      } else {
          getItem();
      }
      return ranArray[ranNum];
  };
  </code></pre>