title: Typescript foreach variable not available
body: <p>I have a foreach loop where I create a new temp array, then run a nested foreach loop. I'm then trying to access the temp array inside the nested foreach loop, but it's coming back with a "variable not available" error.</p>
  
  <pre><code>let final = {
      array: []
  };
  
  myArray.forEach(item =&gt;
  {
      let newObject = { items: [] };
  
      item.subArray.forEach(subItem =&gt;
      {
          var subObject = { prop: subItem.prop };
  
          // Error here: "newObject is not available"
          newObject.items.push(subObject);
      });
  
      // Error here: "final is not available"
      final.array.push(newObject);
  });
  </code></pre>
  
  <p>I know I can provide <code>this</code> to the array by providing it as an argument (eg: <code>item.subArray.forEach(subItem =&gt; {},</code><strong><code>this</code></strong><code>);</code>)</p>
  
  <p>but this doesn't help me because tempArray doesn't exist at the class level.</p>
  
  <p>I have the same problem when I try to assign my temp array to the "final" array declared outside the foreach.</p>
  
  <p>Is there a way I can access the parent scope from within the foreach?</p>
  
  <p><em>I should point out this code exists within a function defined on a class. I'm basically trying to aggregate properties with a certain value from within the subarray</em></p>
  
  <p>Screenshot showing the issue: <a href="http://i.imgur.com/HWCz0Ed.png" rel="nofollow">http://i.imgur.com/HWCz0Ed.png</a><br>
  (The code visible in the image is within the first <code>forEach</code> loop)</p>
  
  <hr>
  
  <p><strong>Update</strong>: I figured this out, it was an issue between using <code>let</code> and <code>var</code>. See my answer below for details.</p>