6

Not a problem, because I found out what causes it, but a huge quirk nevertheless:

Apparently when you create a closure, the JavaScript engine does not save all of its scope variables. It saves only the ones that are really used by the inner function. This causes incorrect results in the debugger if you halt your program. Here is how you can reproduce this

1.Run the following snippet in Chrome:

function foo (){
    var id = 0
    var id2 = 1
    return function foo2(){
        //console.log(id)
        console.log(id2)
        debugger
    }
}

foo()()

Notice that only id2 is defined in the closure scope: Only id2 is defined in the closure scope

2.Uncomment the console.log statement.

There are now two variables in the closure scope There are two variables in the closure scope

Does someone know why this happens (I presume it is to save memory) and are there any other aspects of this that we should be aware of.

Jencel
  • 722
  • 7
  • 17
  • Yes, the variable is optimised out because it is not referenced anywhere. – Qantas 94 Heavy Nov 06 '14 at 10:21
  • I never said it is "incorrect behaviour". – Jencel Nov 06 '14 at 10:55
  • It's not "incorrect results". The unused variable is in fact not part of the scope of the inner function, because it doesn't need to be. When you pass a function back from inside a closure, I doubt if you want the outside scope attached to it clogged up with unused, unnecessary variables. –  Nov 06 '14 at 17:47
  • This is answered here: http://stackoverflow.com/questions/28388530/why-does-chrome-debugger-think-closed-local-variable-is-undefined – Filip Sobczak Mar 16 '15 at 16:16

0 Answers0