0

I can access the array words in global scope but when I try to find an item by typing words[index] , it returns undefined. How can I solve this?

let words = [];

    function fetchWords() {
  fetch("https://www.themealdb.com/api/json/v1/1/categories.php")  
    .then((res) => res.json())   
    .then((data) => {  
      for (let i = 0; i < 13; i++) {   
        words.push(data.categories[i].strCategory);
      }
    });
}

fetchWords();`
console.log(words); //This works   
console.log(words[2]); // But this does not. Why?
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • 1
    Also of interest: [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086). The reason why the first "works" is described here: [Is Chrome's JavaScript console lazy about evaluating arrays?](https://stackoverflow.com/q/4057440). In short, you just log the reference to the array, but when you expand it in the console, you get the state of said array at the time you expand it, not at the time the log was made. – VLAZ Jun 28 '20 at 06:58
  • does data.categories[2].strCategory exist? – Siva K V Jun 28 '20 at 07:07

1 Answers1

1

This is because you call:

console.log(words[2]);

before you fetch the result. You need to await fetchWords before console.log(words[2]);