zhenguoli
zhenguoli

Reputation: 2308

Why nodejs console.log different output format for the same object?

For the following code:

function F() {
}

// Define class fields for F
F.value = [ 1, 2, 3, 4 ];

console.log('F', F); // F function F() { }

console.log(F);      // { [Function: F] value: [ 1, 2, 3, 4 ] }

In the code above, I have define class fields for the constructor F. When I console.log() in node different argument list, the printing result is different for F.
The one is function F() { }, the other is { [Function: F] value: [ 1, 2, 3, 4 ] }. So that's why?
But the output is same in browser console. My node version is v4.2.6 and linux.

Thanks in advance.

Upvotes: 2

Views: 122

Answers (1)

Bergi
Bergi

Reputation: 664217

It might be a bug. There's no good reason to differ.

Why does this happen? console.log delegates to util.format (quite literally), and format distin­guishes between a string for the first argument (that might be a format string) and something else. You can find the exact algorithm here. Basically:

  • when the first argument is a string, placeholders get replaced by the respective values, then further arguments are adjoined. Those are inspected when they are objects or symbols, but just cast to strings and concatenated otherwise.
  • when the first argument is not a string, every value is inspected, then they are concatenated together.

Due to the object check relying on typeof, it does not consider functions to be objects, and your function is directly stringified. This difference between casting and inspecting can also be observed for other values (e.g. console.log("0", "example") vs console.log(0, "example")).

Upvotes: 2

Related Questions