Search code examples
javascriptrecursionreferential-integrity

JavaScript Local Primitive Variable Re-assignment in Recursive Function


I have a recursive function like below

function dfs(row, col) {
  if (grid[row][col] === 0) return true;
  let result = grid[row][col] === 2;
  grid2[row][col] = 0;

  let up = down = left = right = true;      // <--- problematic line

  if (row > 0) up = dfs(row-1, col);
  
  if (row < m-1) down = dfs(row+1, col);
  // down === false here
  
  if (col > 0) left = dfs(row, col-1);
  // down === false here still
  
  if (col < n-1) right = dfs(row, col+1);
  // down === true ??  

  return up && down && left && right && result;
}

I notice that during execution, at some point down = dfs(row+1, col) will assign a false value to down, but 2 lines below after right = dfs(row, col+1) somehow down becomes true again.

This mutation would make sense to me if down was a non-primitive variable like Array or Object and we were passing it around across recursive calls, however it's just a boolean. Furthermore, changing the problematic line to below fixes the problem. (i.e. down no longer gets re-assigned to true)

let up = true, down = true, left = true, right = true;

Does anyone know why this re-assignment happens here? Thanks!


Solution

  • The following line:

    let up = down = left = right = true;
    

    only declares up. down, left, right are assigned from global scope and can get updated by any recursion step since they are not local variables.