user2167582
user2167582

Reputation: 6378

can you turn off javascript garbage collector for a debugging mode?

when I'm debugging javascript I'm constantly running into situations where due to scope issues I'm not able to access variables that were suppose to be provided to me by closure.

I can traverse up a stack level to put myself in the correct scope for this case, but this is quite confusing and doesn't do the trick when you deal with promises / async calls.

I believe this is a feature where garbage collector marks and sweeps unused variables (correct me if I'm wrong).

Is there a mode that I can turn to in order to preserve closure variables (and yes I realize this could cause nothing to be garbage collected, but still useful to have when debugging and should not impact the behavior of the app)

code with this issue:

function hello(arr, foo, bar) { 
  arr.forEach(item => {
    debugger; // HERE `foo`, `arr` and `bar` are reference errors in debugger evaluation
  }); 
  return 1 
} 
hello([1,2,3], 'foo', 'bar')

------------edit-------------

UPDATED EXAMPLE

Upvotes: 1

Views: 208

Answers (1)

the8472
the8472

Reputation: 43115

Assuming that this is actually about outer scopes not being captured in the first place because of optimization decisions - which means garbage collection is not involved - there are things you can try:

let singularity = null;
function blackhole(val) {
  singularity = val;
}

function someScope() {
  var abc = 'abc'
  var arr = [1...100] // pseudocode

  arr.map(n => {
      debugger;
      blackhole(abc); // forces abc to be captured
      // or ...
      eval(""); // eval leads to more conservative optimizations
    })
}

or

function someScope() {
  var abc = 'abc'
  var arr = [1...100] // pseudocode

  // normal functions are not as easily optimized as arrow functions
  arr.map(function() {
    debugger;
  })
}

or, assuming you're using firefox go to about:config and set javascript.options.baselinejit = false.

The general idea is to force the compiler to not perform optimizations that throw away unused outer scopes.

Upvotes: 2

Related Questions