Skip to content

console.log calls inspect function on passed object #8071

Closed
@szwacz

Description

@szwacz

Version: v6.3.1
Platform: any

Code...

console.log({
    inspect: function () {
        return 123;
    },
});

...will print:

123

That's because console.log is using under the hood util.inspect which apparently will call inspect method on given object if finds one.

This behaviour is very suprising and looks like a bug to someone who didn't read that particular doc. As a matter of fact I also maintain library which has inspect method as part of its API. So doing console.log(myLib) will lead to obscure error.

Solution?
Both APIs console and util have status stable so I believe there is no way to alter this behaviour.
But how about starting favouring toString over inspect?
So this code...

console.log({
    inspect: function () {
        return 123;
    },
    toString: function () {
        return 'foo';
    },
});

...will print foo instead of 123.

Then at least I'll be able to define toString method and avoid nasty error for the users of my library.

Metadata

Metadata

Assignees

No one assigned

    Labels

    consoleIssues and PRs related to the console subsystem.docIssues and PRs related to the documentations.utilIssues and PRs related to the built-in util module.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions