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);
});