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.


Post this entry to: » del.icio.us  » Digg  » Furl  » Newsvine  » reddit  » Y!

Somewhat related posts

3 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

Leave a Reply