2

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.

2

1 Answer 1

2

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")).

Sign up to request clarification or add additional context in comments.

1 Comment

Thank your for your great answer. This involves alogrithm of console.log(). When I use console.log() in node, I have found some inconsistent output for the same object. So that's so strang to me. And I want to know why.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.