forEach returns undefined - HELP needed

forEach returns undefined - HELP needed
0

#1

Hey. I’m working on Shopping List App (with brilliant watchandcode.com course) and I’m stuck replacing one “for” loop with .forEach. forEach returns ‘undefined’. I’ve tried to use debugger tool but failed to understand why it can access the list itself but can’t do the same with array’s elements.
Could you please give me a hint on this?
The whole project is here: https://embed.plnkr.co/krXD27eSyL7FHFnWkamq/
Here is the part that works…:

var showOnScreen = {
  displayShoppingList: function() {
    var shoppingUnorderedList = document.querySelector('ul');
    shoppingUnorderedList.innerHTML = '';
    for (var x = 0; x < shoppingList.list.length; x++) {
      var shoppingListItem = document.createElement('li');
      var isBoughtDisplay = '';
      isBoughtDisplay = shoppingList.list[x].isBought ?
        '(x)' + shoppingList.list[x].item + ' ' + shoppingList.list[x].itemCounter : '( )' + shoppingList.list[x].item + ' ' + shoppingList.list[x].itemCounter;
      shoppingListItem.id = x;
      shoppingListItem.textContent = isBoughtDisplay;
      shoppingListItem.appendChild(this.createDeleteButton());
      shoppingUnorderedList.appendChild(shoppingListItem);
    }

…And the part, that gives 'undefined":

shoppingList.list.forEach(function(listItem, position){
      var shoppingListItem = document.createElement('li');
      var isBoughtDisplay = '';
    isBoughtDisplay = shoppingList.list.isBought ?
    '(x)' + shoppingList.list.listItem + ' ' + shoppingList.list.itemCounter : '( )' + shoppingList.list.listItem + ' ' + shoppingList.list.itemCounter;
    shoppingListItem.id = position;
    shoppingListItem.textContent = isBoughtDisplay;
    shoppingListItem.appendChild(showOnScreen.createDeleteButton());
    shoppingUnorderedList.appendChild(shoppingListItem);
    });

#2

I haven’t run your code, but I imagine the issue is here:

shoppingList.list.isBought

shoppingList.list is an array and doesn’t have the property isBought. Inside of your forEach, you want to access listItem.isBought.


#3

In this line, you are currently trying to access shoppingList.list.listItem which shouldn’t exist.

    '(x)' + shoppingList.list.listItem + ' ' + shoppingList.list.itemCounter : '( )' + shoppingList.list.listItem + ' ' + shoppingList.list.itemCounter;

The callback in forEach exposes listItem so you should be referencing that variable instead. This is the current element in the shoppingList.list array in the current iteration. It is equivalent to shoppingList.list[x]. With that said, your newly mapped references would be something like this:

shoppingList.list[x] -> listItem
shoppingList.list[x].item -> listItem.item
shoppingList.list[x].foo -> listItem.foo
// etc..

Hope this helps.

:slight_smile: