Question: I'm trying to update the array with values once the user clicks on an element in the DOM. The elements seem to be pushed into the array inside the anonymous function but outside the function the array is still empty. How can I fix that? Here is the javascript code:

```
function getSelection() {
    var selections = [];

    var container = document.getElementById("main-container");
    var choices = document.querySelectorAll('li');

    choicesLength = choices.length;

    for(var i = 0; i < choicesLength; i++) {

        choices[i].addEventListener("click", function(){
            var position = this.getAttribute("value");
            selections.push(position);
            // logs array and updates with each click 
            console.log(selections);
        });
    }       

    // logs empty array
    console.log(selections);

}

```

Basically, after the items are clicked, the main array needs to be updated with what they clicked. 

Any help would be appreciated. 

Thanks

Answer: 
The function you pass to `addEventListener` won't run until the event happens.

It isn't possible for you to click any of the list items before the `console.log` that runs immediately after the assignment fires.

> 
> Basically, after the items are clicked, the main array needs to be updated with what they clicked.
> 
> 
> 

… and that is what will happen. Look at the results of the `console.log` inside the click handler.
This is about Javascript Scoping , you can lean more about it here:  

[Learn more about Javascript Scoping and hoisting](https://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/)

The first console.log(selection) is local while the last console.log(selection) is 
is global, the two are not the same, that is why it is empty.
Here is the edited form of my solution:

```js
function getSelection() {
  var selections = [];
  var container = document.getElementById("main-container");
  var choices = document.querySelectorAll('li');
  choicesLength = choices.length;
  for (var i = 0; i < choicesLength; i++) {

    choices[i].addEventListener("click",pushArray(i));
  }

  function pushArray(elm) {
  var position = choices[elm].getAttribute("value");
  selections.push(position);
  // logs array and updates with each click 
 console.log(selections);
}
  // logs empty array
  console.log(selections);
}

document.body.addEventListener("load", getSelection());
```

```html
<ul>
  <li value="1">1</li>
  <li value="2">2</li>
  <li value="3">3</li>
  <li value="4">4</li>
  <li value="5">5</li>
  <li value="6">6</li>
  <li value="7">7</li>
  <li value="8">8</li>
  <li value="9">9</li>
  <li value="10">10</li>
</ul>
```