I am setting a variable to be the returned value from a function, players and currentPlayer, however it is saying that variable is undefined when trying to use in another function? is the way I’m setting the variable wrong?
let message = document.getElementById('game-message');
// async allows the use of the "await" keyword
async function setPlayers() {
message.innerHTML = `<p>Name of player One?</p>`;
let player1 = await getUserInput();
message.innerHTML = `<p>Name of player Two</p>`;
let player2 = await getUserInput();
const players = [];
players.push(player1, player2);
return players;
}
var players = setPlayers();
var currentPlayer = players[0];
2
Answers
Then warp it in IIFE (Immediately Invoked function expression) because you need to put
await
when callingsetPlayers
function, so to useawait
, the parent function must be an async function.You shouldn’t pollute the global namespace if you can help it. Try writing code that is self contained or a javascript module. If you need to communicate between namespaces, then an EventTarget with CustomEvent can be used to share data.