title: JS: I'm passing an array to a function and filtering and the array changes outside the function. Why?
body: <p>I have a <code>myFunction1</code> that gets a list of lists stored in the cache that is filtered based on the values of other cells to get a final list to populate a dropdown data validation. This happens in a loop because each cell is gonna have a different set of values in the data validation.</p>
  <p>I realized after some time that when function2 is called, the <code>forEach</code>  function I use to filter the array of arrays into an array is actually modifying <code>myList</code> because in the next iteration the forEach filters the first character of each element in the list and in the next iteration it breaks because some elements were left undefined.</p>
  <p>I'm confused as to why this happens, I know that in Python there is no variable declaration just a name pointing to something that's why a deep copy is necessary. This reminded me of that.</p>
  <p>I found a work around by doing a dummy filter like this: <code>var newList = myList.filter(r =&gt; r[0]);</code>
  But I can't figure out why <code>myList</code> was updated outside the scope of <code>myFunction2</code>. Below are my two functions as example.</p>
  <pre class="lang-js prettyprint-override"><code>function myFunction1() {
    var myList = getFromCache('myList');
  
    var lastRow = sheet.getLastRow();
  
    for (var i = 2; i &lt;= lastRow; i++) {
      var a = sheet.getRange(i, 5);
  
      var b = &quot;someVariable&quot;
  
      if (b) {
        updateUnitsList(b, myList, a);
      }
    }
  }
  </code></pre>
  <pre class="lang-js prettyprint-override"><code>function myFunction2(b, myList, a) {
    if (b === &quot;any&quot;) {
      var newList = myList
      newList.forEach((r, index) =&gt; newList[index] = r[1]);
    } 
  
    // Rest of code
  
  }
  </code></pre>