Javascript Associative Arrays are fun! Aren’t they?


…sometimes. Sometimes they also just make your body shake in fever and give you a hard time figuring what is going on with this world around us.

I guess everybody who learns javascript has to go through these things and therefor this is common sense. On the other hand, being a Smalltalk developer for around two decades, I have learned that people regard Smalltalk as a strange language. Which is not something it holds exclusive rights on, obviously.

So here comes my little anecddote. For our Kontolino.de application, I needed to nail together an ajax request that sends a Seaside callback id together with soem String back to the server. Not that I haven’t done this before. Actually I have done that quite a few times already, using both Smalltalk/Seaside and Javascript.

To make a long story short, I needed to create an Associative Array that looks like this: {“5″:”search text”} – easy, right?

No.

First of all, the “5” is the content of a String variable that was rendered on the server side. And the fact that it is a numeric String seems to make things complicated for Javascript.

Because if you do something like this:

var key="5";
var value=someInputTag.val();
var myArray = new Array();
myArray[key]=value;

you will end up with a very strange looking an array: it will have 5 entries, the first four of which are undefined. In the end, it is not an Associative Array at all. It will contain a fifth entry which is the String you just put there. For javascript, a String containing only digits is the same as a number, because, obviously, I must have meant 5 when I said “5”, right?

Since the code looks so easy and straightforward, I was under the assumption that the fact that my Ajax call didn’t work and my server side Breakpoint was never hit has to do with some strange thing going on with Ajax or my server side Seaside code. So I once again started a lengthy journey to neverwhere, which led nowhere, of course. Only took a few hours and some increasing state of desperation😉

A few DuckDuckGo searches later, I found a few places where people suggest using this:

var key="5";
var value=someInputTag.val();
var myArray = new Object();
myArray[key]=value;

And what can I say? The website now works like I always wanted it to. (Please make sure you look at the two snippets very carefully to find the difference😉 ).

Now I am sure I have to be careful to say anything offending about this, because the moment I hit “Post” here on my blog server, somebody will walk around the corner and tell me this is for a (good?) reason. I hate when I have to, but this is one of the things I just have to accept without asking too many questions.