Search code examples
javascriptrubyconsole.loglanguage-comparisons

Assign console.log value to a variable


How can I assign a JavaScript object to a variable which was printed using console.log?

I am in Chrome console. With Ruby I would use test = _ to access the most recent item printed.


Solution

  • You could override standard console.log() function with your own, adding the behaviour you need:

    console.oldLog = console.log;
    
    console.log = function(value)
    {
        console.oldLog(value);
        window.$log = value;
    };
    
    // Usage
    
    console.log('hello');
    
    $log // Has 'hello' in it
    

    This way, you don't have to change your existing logging code. You could also extend it adding an array and storing the whole history of printed objects/values.