Why are both arrays in this function identical?

Viewed 15

I am having trouble understanding some basic behavior in javascript related to arrays and functions.

I have the following code. The intention behind it is for a function to accept an array of arrays, copy it, change one entry, console.log the copy with the changed entry, undo the change, and log the array again. However, both logs are the same. I wish to understand why.

(Link to replit: https://replit.com/@NoahSegal/IssueWithArrays?v=1)

const board = [
  [0, 0, 0],
  [0, 0, 0],
  [0, 0, 0]
];

const evaluateMove = function(x, y, brd, player) {
  const tempBoard = brd.slice();
  
  // Add move
  tempBoard[x][y] = player;
  console.log('updated')
  console.log(tempBoard); //***


  // Undo move
  tempBoard[x][y] = 0;
  console.log('reverted')
  console.log(tempBoard); //***

  // Why are the two console logs identical?
}

evaluateMove(0, 0, board, 1)

If I comment out the tempBoard[x][y] = 0; both logs show the updated board. It appears that the order of execution of the code inside evaluateMove is this:

const evaluateMove = function(x, y, brd, player) {
  const tempBoard = brd.slice();
  tempBoard[x][y] = player;
  tempBoard[x][y] = 0;
  console.log('updated');
  console.log(tempBoard);
  console.log('reverted');
  console.log(tempBoard);

}

What is going on? How do I get the behavior I intend?

0 Answers
Related