Pablo
Pablo

Reputation: 13580

Accessing closure variables in the console

Given this code

function foo()
{
    var x = 1;

    function bar()
    {
        debugger;
        return x + 1;
    }

    return bar();
}

when I open the Google Chrome's console and and foo() gets executed, the console stops at the debugger line. If I type 'x' in the console, I get Uncaught ReferenceError: x is not defined.

If I want to access x in the console, I have two options:

I noticed that when you put a debugger and the code accessed a scope variable at some point, then I can access it in the console.

I found other threads like this one more or less aksing the same question. Is there a better way to access the closure variables?

Btw I use Version 59.0.3071.104 (Official Build) (64-bit) for Debian 8.

Upvotes: 12

Views: 3908

Answers (1)

Marshal
Marshal

Reputation: 4860

I believe you already got the answer in the other thread you referred to. @OwnageIsMagic said it was because of V8 optimization. If you click the function name in the Call Stack, that variable will be accessible then.

Upvotes: 1

Related Questions