I am writing code to recursively solve a sudoku puzzle. For some reason, I cannot save the solved value to the variable saveGrid, which is initialised globally. console.log(grid) outputs the correct result to the console, but at the bottom, console.log(saveGrid) gives the original unsolved puzzle (sample_grid). saveGrid should only be set once, as console.log(grid) is only called once. Very confused here.
var saveGrid;
const solveGrid = function(grid) {
for (let row = 0; row < 9; row++) {
for (let column = 0; column < 9; column++) {
if (grid[row][column] === 0) {
for (let numberToTry = 1; numberToTry < 10; numberToTry++) {
if (isValidPlacement(grid, numberToTry, row, column)) {
grid[row][column] = numberToTry;
solveGrid(grid)
grid[row][column] = 0;
}
}
return;
}
}
}
console.log(grid)
saveGrid = grid;
}
solveGrid(sample_grid)
console.log(saveGrid)
Edit: I found a sort of solution, where saveGrid can only be stored globally as a primitive data type. No clue as to why.