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?
First override
toString
for your object or the prototype:Then convert to string to see the string representation of the object:
If you don't like the extra typing, you can create a function that logs string representations of its arguments to the console:
Usage:
Update
E2015 provides much nicer syntax for this stuff, but you'll have to use a transpiler like Babel:
If the object is defined by yourself you can always add a toString override.
If you are using Node it might be worth considering
util.inspect
.This will yield:
While the version without inspect prints:
You can extend or override in JS
Here's an example how to stringify a Map object: