Search code examples
javascriptarraysforeachiife

How do I call an array within an IIFE using a forEach loop?


I have an array that's inside an IIFE, then I have a forEach loop that iterates over those array items but I don't know how to then call the function using the forEach loop.

//IIFE - Immediately Invoked Function Expression
let pokemonRepository = (function () {

  //List of Pokemon Characters
  let pokemonList = [
    { name: "Pikachu", height: 1.04, type: 'electric' },
    { name: "Bulbasaur", height: 2.04, type: ['grass', 'poison'] },
    { name: "Squirtle", height: 1.08, type: 'water' },
    { name: "Beedrill", height: 3.03, type: ['bug', 'poison'] },
    { name: "Dragonite", height: 7.03, type: ['dragon', 'flying'] },
    { name: "Igglybuff", height: 1.01, type: ['Normal', 'Fairy'] },
  ]

  function add(pokemon) {
    pokemonList.push(pokemon);
  }

  function getAll() {
    return pokemonList;
  }

  return {
    add: add,
    getAll: getAll
  };
})();

// Test of return functions inside IIFE 
// console.log(pokemonRepository.getAll());
// pokemonRepository.add({ name: 'Sandstorm' });
// console.log(pokemonRepository.getAll()); // [ { name: 'Sandstorm' } ]


// forEach loop
pokemonList.forEach(function (pokemon) {
  if (pokemon.height >= 7) {
    document.write("<div class='card'>" + "<p>" + pokemon.name + " " + "(Height:" + " " + pokemon.height + ") - Wow! that is a big pokemon! " + "</p>" + "</div>");
  } else if (pokemon.height) {
    document.write("<div class='card'>" + "<p>" + pokemon.name + " " + "(Height:" + " " + pokemon.height + ")  " + "</p>" + "</div>")
  }
});

I can call the items in the console.log using;

console.log(pokemonRepository.getAll());

but I want to call the repository using the forEach loop in the DOM.


Solution

  • You answered yourself - getAll returns the array, so you need to call it:

    pokemonRepository.getAll().forEach(function (pokemon) {
      if (pokemon.height >= 7) {
        document.write("<div class='card'>" + "<p>" + pokemon.name + " " + "(Height:" + " " + pokemon.height + ") - Wow! that is a big pokemon! " + "</p>" + "</div>");
      } else if (pokemon.height) {
        document.write("<div class='card'>" + "<p>" + pokemon.name + " " + "(Height:" + " " + pokemon.height + ")  " + "</p>" + "</div>")
      }
    });