Monday, February 18th, 2008

Self Printing JavaScript Literals

Category: JavaScript, Tip

Are you ever sick of seeing Object get printed out when you try to output a variable to your console.

Oliver Steele talks about Self Printing JavaScript Literals where you can clean that up with a toString:


  1. function makeLiteral(name) {return {toString:function(){return name}}}
  2. var L1 = makeLiteral("L1");
  3. var L2 = makeLiteral("L2");
  4. L1
  5. // >>> L1
  6. L2
  7. // >>> L2

Kangax takes it further to support nesting:


  1. function defineLiteral() {
  2.   var o = window, args = arguments, prop;
  3.   for (var i=0, l = arguments.length; i
  4.     prop = arguments[i];
  5.     o[prop] = o[prop] || { }; o = o[prop];
  6.     if (i == l-1) o[‘toString’] = function() {
  7.       return, ’.’)
  8.     }
  9.   }
  10.   return o;
  11. }
  13. defineLiteral(‘bar’, ‘baz’, ‘qux’, ‘quux’); // => bar.baz.qux.quux
  14. bar.baz.qux.quux.toString(); // => ‘bar.baz.qux.quux’

Posted by Dion Almaer at 6:09 am

3 rating from 19 votes


Comments feed TrackBack URI

“Are you ever sick of seeing Object get printed out when you try to output a variable to your console.”

I can’t say that I have. And I can’t even justify all this work just for the sake of debugging.

Comment by urandom — February 18, 2008

I think in FF you can use whatever.source to prettyprint anything.

Comment by Lon42 — February 18, 2008

I must say I agree with Urandom.

Comment by Jordan — February 18, 2008

Functional JavaScript seems like a python language on shell.

Comment by bollywood — February 18, 2008

Alternately, you could implement Python’s polymorphic |repr| or Ruby’s |inspect|. Firebug has good object inspection if you log non-strings (with a browsable object inspector, but I don’t believe it’s overridable. I disagree with Urandom and Lon42; inspection is very valuable for debugging and totally worth the bother to copytheft.

Comment by Kris Kowal — February 18, 2008

I don’t think that they’re saying that inspection isn’t valuable for debugging, I think that it is indispensable, but this particular technique doesn’t really gain you much of anything since modern debuggers (like Firebug) have that feature baked in. There are debuggers for IE and other browsers that provide similar abilities. If you *really* need this ability and don’t have a debugger installed, a property dump of the object would be more useful than just a name.

Comment by Andy Kant — February 18, 2008

Leave a comment

You must be logged in to post a comment.