Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling variables defined in outer function from inner function with debugger

From the jQuery docs javascript guide:

Because local scope works through functions, any functions defined within another have access to variables defined in the outer function:

function outer() {
    var x = 5;
    var y = 2;
    function inner() {
        console.log( x );
        debugger; // <-- !!!
    }
    inner();
}
outer()

Console triggered with debugger:

> x
5
> y
ReferenceError: y is not defined

Since variables defined in the outer function can be used by the inner function (E.g. x or y), why is the debugger not able to call the y variable?

I suspect people will answer that the debugger only shows variables defined in the most inner/local scope. The reason for this being that otherwise no distinction could be made using the debugger between the inner and outer scope when inspecting a variable using the debugger in the inner function. Additionally, every variable defined in an outer scope which is executed in the inner scope allows the debugger to access it.

But if that is the case, isn't there some way to still call the variable y from the console inside the inner function? (using a notation respectful of scope, e.g. outer.y)

Edit: Debuggers in other languages

Apparently this behavior of a debugger is not limited to javascript. The Python debugger pdb for example behaves similarly:

def outer():
    x = 5
    y = 2
    def inner():
        print x
        import pdb; pdb.set_trace()
    inner()
outer()

(Pdb) x
5
(Pdb) y
*** NameError: 'y' is not defined
like image 893
Bentley4 Avatar asked Oct 28 '13 14:10

Bentley4


1 Answers

Presumably this is an optimisation by the JavaScript engine. Since you're not referring to y within the inner function there is no need to hold on to it in the closure. This will allow it to be garbage collected when the outer function returns.

If you add a reference to y (for example console.log(x, y)) you can see the values of both x and y as you would expect.

isn't there some way to still call the variable y from the console inside the inner function?

Apparently not. You could just add a reference to y within inner while debugging (it doesn't have to do anything, any reference will do).

like image 168
James Allardice Avatar answered Oct 29 '22 23:10

James Allardice