I remember that always when I wanted to pass console.log
as a callback parameter to some function, it didn't work unless I used the bind()
method to bind console
to it.
For example:
const callWithTest = callback => callback('test'); callWithTest(console.log); // That didn't use to work. callWithTest(console.log.bind(console)); // That worked (and works) fine.
See Uncaught TypeError: Illegal invocation in javascript.
However, recently I noticed that console.log()
works fine even when called on object other than console. For example:
console.log.call(null, 'test');
logs 'test'
.
When and why did it change? Does the specification say anything about it?
The console. log(JSON. stringify(obj)) method can be useful for logging the object to the console as string, as long as the data in the object is JSON-safe.
Answer: Use console. log() or JSON. stringify() Method This method will print the object in browser console.
console. log specifically is a method for developers to write code to inconspicuously inform the developers what the code is doing. It can be used to alert you that there's an issue, but shouldn't take the place of an interactive debugger when it comes time to debug the code.
Editor's Draft of Console API used to say:
Logging APIs SHOULD all be callable functions allowing them to be passed as arguments to error handling callbacks, forEach methods, etc.
This is no longer included in the current version of the specification.
I thought that Chrome and Node.js changed it to work like in the specification, but it seems that it worked like that even before it.
I'm still curious when did it change and what was the reason of that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With