31

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.

dreftymac
  • 31,404
  • 26
  • 119
  • 182
Dru
  • 9,632
  • 13
  • 49
  • 68

5 Answers5

43

If you want to do this to an object that has been already logged (one time thing), chrome console offers a good solution.

Hover over the printed object in the console, right click, then click on "Store as Global Variable". Chrome will assign it to a temporary var name for you which you can use in the console.

enter image description here

Nick Brady
  • 6,084
  • 1
  • 46
  • 71
  • 6
    This needs more upvotes! Half the answers don't even address the actual question, and this is exactly it. Let's face it: overriding `console.log` is a pain, and I did not remember to do that *before* wanting to look at this thing that got logged. – Thanatos Jan 26 '17 at 19:53
  • What would be the temp var name? – coco97 Aug 25 '20 at 10:15
  • 2
    @coco97 the var name is `temp` with an auto-increment number (i.e. `temp1`, `temp2`, `temp3`, ...). – yeger Oct 21 '20 at 18:59
23

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.

Teun Zengerink
  • 4,277
  • 5
  • 30
  • 32
mirrormx
  • 4,049
  • 1
  • 19
  • 17
18

In Chrome developer tools, you may access last item by $_:

> 1+1;
  2
> $_
  2
Stewie
  • 60,366
  • 20
  • 146
  • 113
  • 5
    Thanks @stewie but this doesn't work for objects printed by console.log (+1 because I didn't know about this feature) – Dru Mar 17 '13 at 15:10
5

Derivative of mirrormx's answer, but more convenient. I don't need to write a function and can just put it in anywhere on the spur of the moment.

console.log(window.$log = data);
mattk
  • 51
  • 1
  • 1
2

Here is chrome reference for comand line api. There is $_ variable but it "Returns the value of the most recently evaluated expression" not printed, you can make your own log function like this:

function log(data){
   console.log(data);
   return data;
}
// after that you can access last printed value by $_

Please, note that my function is for example, console.log possibilities is much more advanced

kirugan
  • 2,514
  • 2
  • 22
  • 41