I was debugging a jQuery code with Chrome and I got stuck on a scope problem.
This is my code:
var foo = "bar";
$.each([1], function(key, value) {
console.log(foo);
console.log("Test");
});
If I put a breakpoint before the second console.log
, I can see foo
among the Closure variables. But if I comment the line before (thus NOT outputting foo
to the console), when I stop at the breakpoint the foo
variable is missing (in fact, a whole Closure level of variables is missing). I tested this code both in Chrome and in Firefox, it has the same odd behaviour.
It's like outputting the variable to the console "stores" it in a new Closure level and exposes those variables.
Am I missing something?
EDIT: Bergi pointed me to the right answer (see garbage collection with node.js).
To summarize it here, when I comment the first console.log
, foo
variable is never used inside theeach
callback and V8 compiler immediately makes it unreachable. If I want to inspect it while debugging I have to use it somewhere, like:
var foo = "bar";
$.each([1], function(key, value) {
console.log("Test");
function test() { console.log(foo); }
});
This way if I stop at the first console.log
, I can inspect the variable as expected.
I could also use the with
statement (but it's deprecated so this probably isn't the right way to approach it ^_^):
var foo = "bar";
with(foo) {
$.each([1], function(key, value) {
console.log("Test");
});
}
The linked answer is about V8, but I think SpiderMonkey (Firefox's JS engine) behaves the same way.