Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Chrome dev tools say variable is not defined? [duplicate]

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();
like image 855
Dustin Avatar asked Apr 14 '18 03:04

Dustin


People also ask

How do I copy a variable value in chrome console?

Right-click an object in Chrome's console and select Store as Global Variable from the context menu. It will return something like temp1 as the variable name. Chrome also has a copy() method, so copy(temp1) in the console should copy that object to your clipboard.

How do I view a variable in Chrome dev tools?

To add a variable to the watch list use the add icon to the right of the section heading. This will open an inline input where you provide the variable name to watch. Once it is filled in press your Enter key to add it to the list. The watcher will show you the current value of the variable as it is added.


1 Answers

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.

like image 194
AnilRedshift Avatar answered Oct 12 '22 05:10

AnilRedshift