To start things off, I'm fairly new to coding and JS, so maybe I'm misunderstanding something very basic here.
I built a script to check a .JSON file for any fields named "ID: XXXX". Its purpose is to return every article's unique identifier from a blog. The unique identifier is "XXXX" in this case.
The script does what it's supposed to, but when I return the values to my global variable article_identifiers, they're returned as a pseudo array. I can't access single values by indexing them via article_identifiers[i].
However, when I set a timeout, article_identifiers is returned as a normal array and I can access the values inside the array by using console.log(article_identifiers[i]).
Here's the code, for context:
var article_identifiers = [];
var url = '/articles.json';
fetch(url)
.then((response) => response.json())
.then(data => {
var article_amount = Object.keys(data.articles).length;
for (var i = 0; i < article_amount; i++) {
article_identifiers.push(data.articles[i].id);
}
})
setTimeout(function(){
console.log(article_identifiers);
},500);
Why do I have to set a timeout? Am I misunderstanding something about the way JavaScript code is processed? Does my console.log() fire before my for loop is finished? If so, why?