Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

console.log() called on object other than console

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?

like image 498
Michał Perłakowski Avatar asked Sep 14 '16 21:09

Michał Perłakowski


People also ask

What function can be used with console log () to write objects to the console?

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.

How do you display an object in console log?

Answer: Use console. log() or JSON. stringify() Method This method will print the object in browser console.

What does console log () do?

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.


1 Answers

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.

like image 107
Michał Perłakowski Avatar answered Oct 11 '22 01:10

Michał Perłakowski