5

I am using eval() to run a script from a string. Below is the code:

eval('console.log("hello")');

I will get hello from the console output. I wonder whether I can save the hello into an variable in the current context. So I am looking for something like this:

const output = eval('console.log("hello")'); // I expect the console output is returned from eval() function.

But I get an undefined response. Is there a way for me to do that?

Venkat
  • 2,478
  • 2
  • 24
  • 56
Joey Yi Zhao
  • 30,508
  • 51
  • 183
  • 377
  • Possible duplicate of [Intercept calls to console.log in Chrome](https://stackoverflow.com/questions/9216441/intercept-calls-to-console-log-in-chrome) – qxg Sep 26 '17 at 03:41
  • 1
    Well console does not return anything so why would you expect it to return something? – epascarello Sep 26 '17 at 03:48

1 Answers1

9

It is impossible because console.log() only returns undefined, however you can make a function that will return something.

Example:

console.oldLog = console.log;
console.log = function(value)
{
    console.oldLog(value);
    return value;
};

const output = eval('console.log("hello")');

Hope this will help.

JohnStands
  • 178
  • 9