jansyb04
jansyb04

Reputation: 161

JS global variable not changing outside of function scope

I'm making a tic-tac-toe game in JS and I'm trying to implement a function inside a 'Game Controller' module that will handle the player's turn. The issue I'm running into is that a global property 'currentPlayer' is not getting its value changed outside of the scope of the function that modifies it.

I've tried debugging using Dev tools and I can see the value changing but only inside the 'switchPlayerTurn' function. Any suggestions here?

const GameController = (() => {
    const activePlayers = [];
    let currentPlayer = ''; 
    
   const _switchPlayerTurn = () => {
        if(currentPlayer === '') {
            currentPlayer = activePlayers[0];
        } else if(currentPlayer === activePlayers[0]){
            currentPlayer = activePlayers[1];
        } else if(currentPlayer === activePlayers[1]){
            currentPlayer = activePlayers[0];
        }
    }

    const init = () => {
        return createPlayers()
        .then(_switchPlayerTurn());
    }

    return {
        init,
        activePlayers,
        currentPlayer,
    }

})();

Upvotes: 0

Views: 1172

Answers (2)

Kinglish
Kinglish

Reputation: 23654

This isn't as elegant as @certainPerformance's answer, but for the sake of completeness... you could always define it outside your function scope so it is accessible globally all the time

let currentPlayer = ''; 
const GameController = (() => {
    const activePlayers = []; 
    // ...

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370689

Returning an object with currentPlayer only results in the object containing the value of currentPlayer at the moment of the return of the object. You need a function instead, so that you can retrieve the current value of the identifier inside on demand.

return {
    init,
    activePlayers,
    getCurrentPlayer: () => currentPlayer,
}

and then, wherever you're using it externally, use .getCurrentPlayer() instead of .currentPlayer

Upvotes: 2

Related Questions