Am trying to add/remove elements from an array declared inside a function. I have been able to add or remove and access the updated array for the same.
For accessing the array I have used two different approaches.
- Have created an inner function which returns the array.
- Have returned the array from the main function and accessing the same using dot notation.
Here is my code:
function test() {
  let myArr = [];
  const getMyArr = () => myArr;
  const add = n => {
    myArr.push(n);
    return () => {
      myArr = myArr.filter(a => a !== n);
    };
  };
  return {
    myArr,
    getMyArr,
    add
  };
}
let myTestRun = test();
let remove3 = myTestRun.add(3);
let remove7 = myTestRun.add(7);
let remove8 = myTestRun.add(8);
console.log("myArr after insertion", myTestRun.myArr);
console.log("getMyArr() after insertion", myTestRun.getMyArr());
remove7();
console.log("myArr after removing", myTestRun.myArr); //still returns the old array without any modifications
console.log("getMyArr() after removing", myTestRun.getMyArr()); //returns the modified array. how? Why didn't it work before?What I do not understand is why did myArr did not have any modifications and how come getMyArr() function has returned the updated value. I used to believe that both the myArr point to the same object. So, any modifications on the myArr should be reflected via both the approaches. Why am I wrong. What is the reason behind this different return values?  Please explain.
 
     
     
    