Global Variables in JavaScript

Global variables are an absolute no-go.
End of post?
No, of course not. But there is one nagging detail in ECMAScript that allows for so called implied global variables. You can get them quite easily, just forget to add a declaration var ident; and you have one. JavaScript knows now real variable scope, only inside and outside a function so it assumes it was a global variable (his might not be the case with every browser and other engine but it was in older ones, so YMMV) even if it is just a misspelling of a local variable. That can lead to some very interesting debugging sessions if the lines of code are legion and carefully spaghettified.
I don’t think there is a solution for it. You can try JSlint but it is a it behind, closed-source (or I just couldn’t find it) online, so one does not know what happens to your data.

But that rant was just a digress, not what I wanted to talk about.

ECMAScript is single threaded, global variables are a very small problem in such an environment, but you can have so called Web-Workers a very limited form of threads introduced in the HTML5 standard. With multi-core CPUs so common, even in cell-phones it starts to make sense. This ignores the fact that the JavaScript engine must translate the web workers into something that is not only threadable but supports multi-cores,too.

Now, global variables are a real problem. Webworker are a very primitive form of threads, as mentioned above, so none of the useful things from e.g.: the Posix threads exist. You can start it, end it, send messages to it and let it send messages to you. You can only send one Object as it seems but that is enough as you can use JSON or equivalent to tie up a parcel, pardon Object. This packet seems to get passed as a full copy, so be aware of memory restrictions. Which limits you can’t find within JavaScript btw. But if the packets are small and the processing is not only heavy but also parallelizable (say that ten times fast đŸ˜‰ ) it makes sense to use web-workers.

Now what to do with global variables; how to get and more so how to set them concurrently?

The Posix threads have a couple of quite nasty but very useful things to handle that, Web-Workers don’t. The don’t know anything about shared memory, they just don’t have shared memory. Webworkers are just some glorified processes.

If you need only small amounts of shared memory, say up to 2.5 MB than you can make use of some of the small external storages the new ECMAScript offers, for example localStorage, although it can only save strings.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s