Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

274
Views
JavaScript saving variable inside recursive function to a global variable

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!