Write out the fields of a JavaScript object

I’ve found myself writing this bit of code a few times now, so thought I’d dump it here for future copy-and-paste.

function writeObj(obj, message) {
  if (!message) { message = obj; }
  var details = "*****************" + "\n" + message + "\n";
  var fieldContents;
  for (var field in obj) {
    fieldContents = obj[field];
    if (typeof(fieldContents) == "function") {
      fieldContents = "(function)";
    details += "  " + field + ": " + fieldContents + "\n";

This just dumps all the object’s fields into the debugging console provided by the Firebug extension for Firefox (the console.log(...) call). If you don’t have Firebug, you can easily create a custom console object to provide an alternative log method. For example, put this snippet at the top of the script to use window.alert(...) when console is undefined:

if (!console) {
  var console = {log: function(details) { window.alert(details); }}

There are probably better ways of doing this, but I find this handy so I can quickly mash writeObj(myObject) into the console and get a list of all the object’s fields. For more fun with simple JavaScript reflection have a look at my earlier post on the subject.