0

I am currently working on a project and I came across a problem and shown below is the same problem but on a smaller scale. A module is to receive an array from another module and a forEach loop is used to iterate through this array to get a particular item. However, after this item is gotten in the forEach loop, it can't be used outside this forEach loop. Please, how do I resolve this? Code is below.

// Module that makes the array
const MakeArray = (() => {
  function CreateObj(name, examples, alive) {
    return {name, examples, alive};
  }

  let nonLiving = CreateObj('Non Living', [], false);
  let living = CreateObj('Living', [], true);
  
  const mainArray = [nonLiving, living];

  return {mainArray};
})();

// Module that gets the array
const getArray = (() => {
  const button = document.querySelector('button');

  MakeArray.mainArray.forEach(item => {
    if (item.alive === true) {
      let itemArray = item.examples;
    }
  });

  function showAlive() {
    button.addEventListener('click', () => {
      itemArray.push('Dog');
      itemArray.push('Cat');
      itemArray.push('Rabbit');

      console.log(itemArray);
    });
  }

  showAlive();
})();
body {
  display: flex;
  height: 100vh;
  justify-content: center;
  align-items: center;
}
<button>
  Add Examples
</button>
Gozman
  • 27
  • 4
  • You’re looking for [`find`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find), not [`forEach`](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach). – Sebastian Simon Nov 08 '22 at 00:21

0 Answers0