Fetch variable can't be accessed outside of statement, even when declared in global scope

Essentially, I’m working on a bot to play the game Wordle. I’m relatively new to JS, but I have intermediate knowledge of Python.

Anyways, I have this code here:

let wordList = []
var newWordList = []

fetch("wordleanswers.json")

    .then(response =>response.json())

    .then(data=>{

        let word = data

        for(const singleData in data){

            wordList.push(singleData);

        }

    }) .then(() =>{
        newWordList = wordList[0].split("\n");

    })

console.log(newWordList);

The variable names will be changed after I get this working and go over the code again.

The issue I’m having is that if I console.log(newWordList), outside of the fetch statement, then I just get an empty array. Is there a way that I can access this without getting the empty array?

A promise will run asynchronously. Meaning the fetch will only run after the console.log()

1 Like