Home > Software engineering >  Why do some functions recognize this global variable but others don't?
Why do some functions recognize this global variable but others don't?

Time:12-03

So I have the following JS function that adds rows to a table based on a global list, events. Events starts out empty and I have another function pushing dict object into it. Items are pushed to the list successfully, however, when events reaches fillTable(), it's empty. In the code below, the first console.log(events) (inside fillTable()), prints an empty list but the second console.log(events) prints the data as expected. events isn't being defined anywhere else so I am lost.

events = []

function otherFunction(repo, type, url) {
    events.push({'repo': repo, 'type': type, 'url': url})
}

function fillTable() {

    console.log(events);         // {}
    console.log(events.length);  // 0

    var table = document.getElementById("table")
    for (let i = 0; i < events.length; i  ) {
        let event = events[i];

        const repo = document.createElement('td')
        repo.appendChild(document.createTextNode(event['repo']));

        const type = document.createElement('td')
        type.appendChild(document.createTextNode(event['type']));
        
        const url = document.createElement('td')
        url.appendChild(document.createTextNode(event['url']));

        const row = document.createElement('tr')
        row.appendChild(repo);
        row.appendChild(type);
        row.appendChild(url);
        table.appendChild(row);
    }
}

otherFunction('a', 'b', 'c');
console.log(events);         // {'repo': 'a', 'type': 'b', 'url': 'c'}
console.log(events.length);  // 1

fillTable();

CodePudding user response:

This is a problem with your usage of async functions.

events = []
getGithubActivity();//this function makes an xmlHttp request
fillTable();//this function is called straight after. There has been no chance for a return of the xmlHttp request.

i suggest placing fillTable like this

request.onreadystatechange = function () {
        if (request.readyState == 4 && request.status == 200) {
            try {
                //add events
               fillTable();
            }
            catch (e) {
                console.log('getGithubActivity() - Error: '   e);
            }
        }
    };

When you log an object in console. It will update upon being opened, this is why it appears filled to you even though at the time of logging the length was 0. By the time you open it in console, the request has returned.

Also I noticed that eventList isn't defined anywhere, could this possibly be a typo?

  • Related