In interview, I was asked that any string for e.g. "Hello" should be consoled when below line of code is executed.
console.log(new X())
This should be achieved without any additional console.log statements.
I tried something like:
function X() { return "Hello"; }
But it is not returning a string. It is returning the newly created instance of X.
Was this a trick question?
tl; dr;
Explanation:
An immediate thought is to somehow use
toString, but it doesn't work. Logging a plain object or class that implementstoStringwill still output the object structure when you log it, so that won't work.2 parts of the spec are key to solve this:
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new)
You have little control of how a user defined class will be logged. But maybe there is a built in object that will log text, so we need to figure out what that might be, and then return it in the constructor. What built in objects log text?
(https://console.spec.whatwg.org/)
^^ Paydirt. We need to find an object that has an "optimally useful formatting" which is not the object tree. I couldn't find an exhaustive list, but lets think about it. I know offhand that logging a dom node logs the html tree instead of the object tree:
So I took a leap and guessed that logging a text node might just log the text, and it worked:
and there it is
see also: