0

I try to make a simple to do list but when I put let shoppingList = []; inside addItem() function it's not working. Why this is happening?

let shoppingList = [];

function addItem() {

  let Item = document.getElementById("item").value;
  let output = document.getElementById("output");
  let html = '';

  if (shoppingList.indexOf(Item) === -1) {
    shoppingList.push(Item);
  }

  for (var x = 0; x < shoppingList.length; x++) {
    html += (x + 1) + ". " + shoppingList[x] + "<br>";
  }

  output.innerHTML = html;

}
2
  • 2
    If you put let shoppingList = []; inside the function you'll get a new empty list every time the function is called. It sounds like that's not what you want. Commented Dec 15, 2018 at 5:49
  • 1
    Where is the Html code? Commented Dec 15, 2018 at 5:50

1 Answer 1

2

If you put your shoppingList array inside the function, it will create a new copy of an array - an empty one - every time the function is called, so every time the function is called it will work with a new array.

If your array is global (defined outside of the function), as in your code sample, it keeps the added values between calls.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.