7

In the code below, when paused at the breakpoint, Chrome Dev Tools will tell me "foo" is or is not defined depending on whether or not the console.log line is commented out or not.

Once at the breakpoint, if you type "foo" in the console, or add it as a watch variable, if the console statement is commented out it will say foo is undefined, however if the console statement is not commented out, then it will correctly show the value of foo (1). Why is this happening?

function func1(){

    let foo = 1; 

    var func2 = function (){
        function func3 (){
            let foo2 = 4;
            // put breakpoint here
            let foo3 = 5;
            // console.log(foo);  //says foo is undefined when this line commented
        }
        func3();
    }
    func2();
}

func1();
Dustin
  • 71
  • 2
  • 5

1 Answers1

5

The chrome debugger is nuanced about capturing variables.

Since your inner func3 does NOT reference foo, then inside the debugger, you won't be able to console log it - EVEN though if you wrote real code, it would work.

Try this:

function func1(){

    let foo = 1; 

    var func2 = function (){
        function func3 (){
            let foo2 = 4;
            foo; // Note that I'm just referencing the variable, not doing anything with it
            // put breakpoint here
            let foo3 = 5;
            // console.log(foo);  //says foo is undefined when this line commented
        }
        func3();
    }
    func2();
}

func1();

Just by adding foo; to the inner function, now the debugger will make it available to you.

AnilRedshift
  • 7,937
  • 7
  • 35
  • 59
  • You "answer" implies this is a chrome specific issue. "If I'm not mistaken" - this happens in all browsers... – Seth McClaine Apr 14 '18 at 03:27
  • @SethMcClaine According to the poster in the related question, in Firebox the debugger behaves as expected and the variable is visible to the debugger even without real code referencing it. – Dustin Apr 14 '18 at 16:27
  • 1
    @SethMcClaine AFAIK this is specific to the chrome debugger – AnilRedshift Apr 15 '18 at 00:16