Is it possible to override JavaScript's toString() function to provide meaningful output for debugging?

devios1 picture devios1 · Jun 10, 2011 · Viewed 87.7k times · Source

When I console.log() an object in my JavaScript program, I just see the output [object Object], which is not very helpful in figuring out what object (or even what type of object) it is.

In C# I'm used to overriding ToString() to be able to customize the debugger representation of an object. Is there anything similar I can do in JavaScript?

Answer

Michael Spector picture Michael Spector · Jun 10, 2011

You can override toString in Javascript as well. See example:

function Foo() {}

// toString override added to prototype of Foo class
Foo.prototype.toString = function() {
  return "[object Foo]";
}

var f = new Foo();
console.log("" + f); // console displays [object Foo]

See this discussion on how to determine object type name in JavaScript.