JavaScript: Calling the unnamed

How does this look like?

o[""]()

A bit like a syntax error, eh? Or an emoticon of some sort. Well, it's valid JavaScript code.

JavaScript objects can have an empty string as a name for a property/method. So if you create an unnamed method called "", you can't call it using the dot notation, but you can, using the brackets.

So type this in your Firebug console:

var o = {
  "": function(){
        console.log('here')
      }
}

then call the unnamed like o[""]()

It works!

Reminds me of the Wizard of Earthsea a little bit where you had to know the true names of things in order to do the wizardry.

This entry was posted on Thursday, August 16th, 2007 and is filed under JavaScript. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.


Get notification for future posts: follow me on Twitter or subscribe to my RSS feed

Somewhat related posts

4 Responses to “JavaScript: Calling the unnamed”

  1. qureyoon Says:

    “Reminds me of the Wizard of Earthsea a little bit where you had to know the true names of things in order to do the wizardry.”

    or as in Eragon too ;)

    nice article btw ^^

  2. steve Says:

    Yeah, since the [] square brackets allow you to access any “key” member of the object, any unique key works… including [""] empty string, even [null] works, as does [true] and [false].

    Now, if there were only some real useful purpose for this… hmmm

  3. Stoyan Says:

    True, can’t think of any purpose. Apart from job security by writing unmaintainable code ;)

    Here’s another one from the “this is not a syntax error” department:

    alert("test"[1])

    And another one: http://www.wait-till-i.com/index.php?p=284

  4. HB Says:

    Weird. I wonder if there’s some sort of compression/optimization value to this. One less variable “name” in there. Definitely odd to look at though.

Leave a Reply