Home > OS >  What does console.log use to convert this to string?
What does console.log use to convert this to string?

Time:08-06

What does console.log use to convert a variable into a string?

 console.log('DEBUGGING', this, JSON.stringify(this), String(this), this.toString(), `${this}`);

I'm logging the above and receiving:

DEBUGGING restaurant undefined class extends Model {} class extends Model {} class extends Model

I need the restaurant string saved to a variable, however only console.log logs this - every other method of converting to a string produces class extends Model {} which is useless to me.

CodePudding user response:

As per the comments, I was told this was Node. OP, please include that in your question in the future!

If I was to write my own implementation of console.log, it would probably look similar to the following:

const util = require('util');
console.log = function log(...params) {
    process.stdout.write(params.map(v => typeof v === 'string' ? v : util.inspect(v))   '\n');
}

Notice util.inspect()? That's the magic. You can read up on it by clicking the link to the docs (same link as earlier).

  • Related