Search code examples
javascriptclosures

Why is my chess table not resetting before populating it?


I'm making a chess game and I start with an initial board. I have a position changing feature based on FEN. But when I want to update the board and reset before adding the new squares, it doesn't reset.

const board = () => {
    let squares = [];

    const setBoard = fen => {
        squares = [];
        //populating squares logic
    };

    return { squares, setBoard };
};

This is where I invoke this function:

const startingFEN = "r1b1kb1r/ppp1pp1p/2nq1np1/3p4/3P1Q2/1P2P1P1/P1P2P1P/RNB1KBNR w KQkq - 0 1";

const chessBoard = board();
chessBoard.setBoard(startingFEN);
drawBoard(chessBoard.squares);

And this is where I update the board (dom.js)

fenButton.addEventListener("click", () => {
    chessBoard.setBoard(fenInput.textContent);
    drawBoard(chessBoard.squares);
});

the squares = [] line in the setBoard function breaks the code, but without that line, it just adds an other board without resetting the previous one.


Solution

  • The function returns a reference to the array in the squares variable. By changing the value of a variable in a function, you do not change the passed value.

    To clear an array in a variable, use array.length = 0.

    Since the value of the variable should not change, use const.

    const board = () => {
        const squares = []; // use 'const'
    
        const setBoard = fen => {
            squares.length = 0; // clear squares
            //populating squares logic
        };
    
        return { squares, setBoard };
    };