Nicolas Mesa

Dad, husband, geek

How to Access Logged Objects in the Javascript Console

In this short post, we go through the process of making a console.logged Object available in Chrome’s javascript console.

TLDR

Right-click the Object you want to inspect and click Store as global variable. This creates a variable with name temp<n> where <n> is a number (starts from 1). Use the variable to access the Object.

Explanation

The Hack Version

Sometimes when I’m debugging, I need to access an Object and its methods from the Javascript console. To do this, I have to fire up the debugger and step into the function until I get access to the object I want, or I have to come up with a hack like the following:

function superNestedFunction() {
    const obj = getObj();
    console.log(obj);

    // hack
    window.myObj = obj;

    // Do something interesting with obj
}

For this discussion, let’s say the getMyObj() function returns an object like this:

function getObj() {
    return {
        prop: 'Hello World',
        fn: function() {
            console.log('Inside myObj.fn');
        }
    };
}

Then, from the console, I can do:

superNestedFunction(); // Logs: {prop: "Hello World", fn: ƒ}
window.myObj.prop; // Logs: "Hello World"
window.myObj.fn(); // Logs: Inside myObj.fn

Note that this is a terrible hack! As much as I hate having a bunch of objects in my logs, I think it’s a lot worse to pollute the global namespace (especially when you forget to remove that hack). Let’s look at a better way of doing this.

The better version

We’re going to use the same example that we had before (minus the hack). The entire code looks like this:

function superNestedFunction() {
    const obj = getObj();
    console.log(obj); // We're still logging the object

    // Do something interesting with obj
}

function getObj() {
    return {
        prop: 'Hello World',
        fn: function() {
            console.log('Inside myObj.fn');
        }
    };
}

superNestedFunction(); // Logs: {prop: "Hello World", fn: ƒ}

Now right-click on the logged Object and select the Store as global variable option.

Right click on the Object an select "Store as global variable"

Chrome automatically creates a new global temporary variable (temp1 in this case) and assigns it the Object that you right-clicked:

Global variable "temp1" created by Chrome

Now you can use temp1 to access any field of that Object! Let’s see the whole thing in action:

Conclusion

We went through the steps to assign a logged object to a global variable and were able to access its properties and functions. Note that this is not a replacement for the debugger, it’s just a convenient way to explore an Object. Especially if the console.log is already there.

Happy debugging!


Share